classSolution{public:Node*inorderSuccessor(Node*node){// the successor is somewhere lower in the right subtreeif(node->right){node=node->right;while(node->left)node=node->left;returnnode;}// the successor is somewhere upper in the treewhile(node->parent&&node->parent->left!=node)node=node->parent;returnnode->parent;}};
JAVA
classSolution{publicNodeinorderSuccessor(Nodenode){// the successor is somewhere upper in the treeif(node.right==null){while(node.parent!=null&&node.parent.left!=node)node=node.parent;returnnode.parent;}// the successor is somewhere lower in the right subtreenode=node.right;while(node.left!=null)node=node.left;returnnode;}}
Login to Codeflu
Log in to stay update and get notify on new arrivals.