0%

面试题 04.06. 后继者

面试题 04.06. 后继者

中序遍历
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
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; // 记录路上大于p中最小的点
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)