[LeetCode]Inorder Successor in BST

来源:互联网 发布:淘宝订单报表 编辑:程序博客网 时间:2024/05/23 19:22

题目: Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

返回一棵BST中给定节点的中序遍历后继节点。就是在中序遍历的顺序中,给定点下一个要遍历的点。

方法一:直观逻辑

在BST中,进行二分搜索,找到所给节点,然后判断:
1、所给节点p有右子节点,那么后继节点就是右子树的最左节点。
2、所给节点是孩子节点,且之前有父节点,那么依次取出父节点,直到某个n级的点是n-1级父节点的左子节点,那么后继节点就是n-1级父节点。

用一个栈记录遍历过的父节点,代码如下:

public class Solution {    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {        return dfs(root, p, new Stack<>());    }    private TreeNode dfs(TreeNode root, TreeNode p, Stack<TreeNode> stack) {        if (root == null) return null;        TreeNode res;        if (p.val > root.val){            stack.push(root);            res = dfs(root.right, p, stack);        }        else if (p.val < root.val){            stack.push(root);            res = dfs(root.left, p, stack);        }        else {            if (root.right != null){                root = root.right;                while (root.left != null) root = root.left;                return root;            }else if (stack.isEmpty()) return null;            else {                TreeNode cur = root;                while (!stack.isEmpty()) {                    if (stack.peek().left == cur) return stack.peek();                    else cur = stack.pop();                }                return null;            }        }        return res;    }}

方法二:分治思想

上面的代码很复杂度还可以,但是实现十分的复杂,采用分治的思想,去分析每一个节点。

对于每一个节点,如果目标节点小于当前节点,那么目标节点应该在左子树,同时后继节点可能由左子树中产生,然而如果左子树返回节点为空,那么后继节点其实就是当前节点。

如果目标节点大于或者等于当前节点,后继节点都一定在右子树中。

可得代码如下:

public TreeNode successor(TreeNode root, TreeNode p) {  if (root == null)    return null;    //后继一定在右子树中  if (root.val <= p.val) {    return successor(root.right, p);  } else {  //后继在左子树或者是当前节点    TreeNode left = successor(root.left, p);    return (left != null) ? left : root;  }}
0 0
原创粉丝点击