Leetcode - 285.Inorder Successor in BST

来源:互联网 发布:手机淘宝能投诉卖家吗 编辑:程序博客网 时间:2024/06/10 06:18

Problem Description:
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.


Analysis :
The easier one: p has right subtree, then its successor is just the leftmost child of its right subtree;
The harder one: p has no right subtree, then a traversal is needed to find its successor.
For harder one :
We search from the root, each time we meet a node which val is greater than p -> val, we know that this node maybe its successor, So we record this node in suc. Then try to find the node in next level.
if (p->val < root -> val) root = root -> left;
else (p -> val > root -> val) root = root -> right;
Once we find p -> val == root -> val, we know we’ve reached at p and the current suc is just its successor.


Code:

class Solution {public:    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {        if (p -> right) return leftMost(p -> right);        TreeNode* suc = NULL;        while (root) {            if (p -> val < root -> val) {                suc = root;                root = root -> left;            }            else if (p -> val > root -> val)                root = root -> right;             else break;        }        return suc;    }private:    TreeNode* leftMost(TreeNode* node) {        while (node -> left) node = node -> left;        return node;    }};
0 0
原创粉丝点击