Inorder Successor in Binary Search Tree



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, returnnull.

分析:

给一个二叉查找树,以及一个节点,求该节点的中序遍历后继,如果没有返回 null。

一棵BST定义为:

节点的左子树中的值要严格小于该节点的值。
节点的右子树中的值要严格大于该节点的值。
左右子树也必须是二叉查找树。
一个节点的树也是二叉查找树。

这道题的中心思想就是先把root结点移动到p旁边去,因为binary search tree的特点是 左子树小于 根,根小于右子树。

while(root不为空,并且root和p不相等)

      如果判断了root .val > p.val,就说明在根的左侧,所以一点一点往左移动,直到root 为空,或者root等于p.

      如果根小于p,说明在右侧,要右移.

关于返回值

1.如果P没有右子节点,而且P是他父节点的左孩子,则要找的后继节点就是他的父节点
2. 如果P没有右子节点,而且P是他父节点的右孩子,则要找的后继节点就是他祖先节点里第一个是他父节点左子树的节点的父节点


3. 如果P有右子节点,则要找的后继节点就是以它右孩子为根的子树的最左面那个节点.

1 2对应的是程序里 return successor那部分
3 对应的是最下面那部分

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode successor =  null;
        while (root != null && root != p) {
            if (root.val > p.val) {
                successor = root;
                root = root .left;
            } else {
                root = root.right;
            }
        }
        
        if (root == null) {
            return null;
        }
        
        if (root.right == null) {
            return successor;
        }
        
        root = root.right;
        if (root.left != null) {
            root = root.left;
        }
        return root;
    }
}

定义后继点,

根非空,根不等p进循环

根大p则 后继为根 根左移。

小等则左移,

退循环

根空返空,

根右空,返后继,

根右移,

root向左走到头,

返回根

原文地址:https://www.cnblogs.com/iwangzheng/p/5770807.html