Given a binary search tree (See Definition) and a node in it, find the in-order successor of that node in the BST.
If the given node has no in-order successor in the tree, return null
.
Example
Example 1:
Input: {1,#,2}, node with value 1
Output: 2
Explanation:
1
\
2
Example 2:
Input: {2,1,3}, node with value 1
Output: 2
Explanation:
2
/ \
1 3
Challenge
O(h), where h is the height of the BST.
Notice
It's guaranteed p is one node in the given tree. (You can directly compare the memory address to find p)
分析
这道题要求找到给定p的下一个中序遍历值,其实就是搜索二叉树中序排序后的下一个大于p->val的值。这道题可以分为两种场景,1. p->right != NULL, 那么此时p的下一个值其实就是p->right子树中的最小的值,这个很容易获取。2. p->right == NULL, 那么此时要获取的值一定是root到p路径上的一个大于p->val的节点,这样的话我们可以用stack保存root到p的路径,然后依次弹出stack直到找到一个节点大于p即可。
Code
/**
* 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:
/*
* @param root: The root of the BST.
* @param p: You need find the successor node of p.
* @return: Successor of p.
*/
TreeNode * inorderSuccessor(TreeNode * root, TreeNode * p) {
// write your code here
stack<TreeNode*> q;
if (!root)
return NULL;
if (p->right)
{
return getMinNode(p->right);
}
TreeNode* t = root;
while (t != p)
{
if (t->val < p->val)
{
q.push(t);
t = t->right;
}
else
{
q.push(t);
t = t->left;
}
}
while(!q.empty())
{
TreeNode* f = q.top();
q.pop();
if (f->val > p->val)
return f;
}
return NULL;
}
TreeNode* getMinNode(TreeNode* root)
{
if (!root)
return NULL;
if (!root->left)
return root;
return getMinNode(root->left);
}
};
运行效率
Your submission beats 51.00% Submissions!