Inorder Successor in BST Leetcode

本文探讨了在二叉搜索树中找到指定节点的中序后继节点的方法。介绍了递归与非递归两种实现方式,并通过示例代码详细解释了每种方法的实现细节。

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.

 

好久没做tree的题目,感觉手又生了。。。做了好久还复杂度很高。。。心酸。。。。
当知道大小的时候舍弃另一半的tree。
public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) {
            return null;
        }
        List<TreeNode> res = new ArrayList<>();
        helper(root, res, p);
        for (int i = 0; i < res.size(); i++) {
            if (res.get(i) == p && i != res.size() - 1) {
                return res.get(i + 1);
            }
        }
        return null;
    }
    private void helper(TreeNode root, List<TreeNode> res, TreeNode p) {
        if (root == null) {
            return;
        }
        if (root.val > p.val) {
            helper(root.left, res, p);
        }
        res.add(root);
        if (root.val <= p.val) {
            helper(root.right, res, p);
        }
    }
}

非递归方法:

1.如果p有右子树,那么从右子树里面找最小值。 

2.如果p没有右子树,那么离它最近的比它大的parent就是它的successor。

public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) {
            return null;
        }
        if (p.right != null) {
            return helper(p.right);
        }
        TreeNode parent = null;
        while (root != null && root != p) {
            if (root.val > p.val) {
                parent = root;
                root = root.left;
            } else {
                root = root.right;
            }
        }
        return parent;
    }
    public TreeNode helper(TreeNode node) {
        if (node.left == null) {
            return node;
        }
        return helper(node.left);
    }
}

这道题做了又放下今天又翻出来做。。。看了top solution人家就是很有水平的。。。差距啊。。。

递归方法:

思路也有些类似,但也不知道人家怎么想出来的。。。。

1.如果p有右子树(右子树节点不为null),那么从右子树中寻找最左边的节点。

2.如果p没有右子树了,那么相当于右子树最左边的节点是null,此时返回离它最近的比它大的root节点。

哎这个方法还是以后再回顾一下吧。。。。

public class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null) {
            return null;
        }
        if (root.val <= p.val) {
            return inorderSuccessor(root.right, p);
        } else {
            TreeNode left = inorderSuccessor(root.left, p);
            return left != null ? left : root;
        }
    }
}

转载于:https://www.cnblogs.com/aprilyang/p/6404107.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值