您的位置:首页 > 其它

[leetcode] 285. Inorder Successor in BST 解题报告

2016-03-14 14:39 771 查看
题目链接: https://leetcode.com/problems/inorder-successor-in-bst/
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return
null
.

思路: 一种较为通用的方法是中序遍历一遍二叉树,记录结点的前一个结点,这样当前一个结点为p时,当前结点就是p的后继结点.这种方法适用于一般二叉树,时间复杂度为O(n).

但是这种方法并没有利用到二叉搜索树的性质. 因此我们还可以比较给定结点与根结点的大小, 如果根节点的值较大, 说明这个结点在根节点的左边, 因此此时根节点就是其不紧切后继, 然后再往左子树去比较. 如果根节点值较小, 说明我们要找的结点在根节点右边.这样一步步就可以找到最终的后继.

各自代码如下:

1.

/**
* 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) {
if(!root) return root;
inorderSuccessor(root->left, p);
if(pre == p) ans = root;
pre = root;
inorderSuccessor(root->right, p);
return ans;
}
private:
TreeNode *pre = NULL, *ans = NULL;
};


2.

/**
* 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) {
if(!root || !p) return NULL;
TreeNode* ans = NULL;
while(root)
{
if(root->val > p->val)
{
ans = root;
root = root->left;
}
else root = root->right;
}
return ans;
}
};
第二种参考: https://leetcode.com/discuss/86078/sharing-my-36ms-c-solution
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: