LeetCode 285. Inorder Successor in BST
找中序遍历的后一个节点,那就中序遍历到当前节点后再往后一个,可以用递归,也可以非递归,完全没有用到BST的性质。
class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { stack<TreeNode *> s; TreeNode *cur=root; bool flag=false; while (!s.empty() || cur!=NULL){ while (cur){ s.push(cur); cur = cur->left; } cur = s.top(); s.pop(); if (flag) return cur; if (cur==p) flag=true; cur = cur->right; } return NULL; } };
也可以充分利用BST的性质,如果p比当前节点小,说明在左子树,res=root;否则去右子树搜索。
class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { TreeNode *res=NULL; while (root!=NULL){ if (p->val<root->val){ res = root; root = root->left; }else root = root->right; } return res; } };
用递归写
class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { if (root==NULL) return NULL; if (p->val<root->val){ TreeNode *left=inorderSuccessor(root->left,p); return left!=NULL?left:root; }else return inorderSuccessor(root->right,p); } };
引申一下,如果求前面一个节点,也是一样做,只不过left right反一反。

浙公网安备 33010602011771号