中序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { TreeNode* pre = nullptr; TreeNode* cur = root; stack<TreeNode*> s; while(!s.empty() || cur) { while(cur) { s.push(cur); cur = cur->left; } cur = s.top(); s.pop(); if(pre == p) return cur; pre = cur; cur = cur->right; } return nullptr; } };
|
利用bst性质
后继节点是大于他中的最小的数
如果这个节点有右子树,后继节点就是右子树的最左边,如果没有,后继节点就是他路上最小的一个。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { TreeNode* cur = root; TreeNode* ans = nullptr; while(cur) { if(cur->val > p->val && (!ans || ans->val > cur->val)) ans = cur; if(cur == p) { if(cur->right) { cur = cur->right; while(cur->left) cur = cur->left; return cur; }else return ans; }else { if(cur->val > p->val) cur = cur->left; else cur = cur->right; } } return nullptr; } };
|
O(logn)