285. Inorder Successor in BST

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.

Solution

题目要审清楚:

  • BST
  • Successor是后继者

Stack, time O(n), space O(n)

这种解法是binary tree通用的,没有考虑bst的特性。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null || p == null) {
            return null;
        }
        
        Stack<TreeNode> stack = new Stack<>();
        pushAllLeft(root, stack);
        boolean found = false;
        
        while (!stack.empty()) {
            TreeNode curr = stack.pop();
            
            if (curr == p) {
                found = true;
            } else if (found) {
                return curr;
            }
            
            pushAllLeft(curr.right, stack);
        }
        
        return null;
    }
    
    public void pushAllLeft(TreeNode node, Stack<TreeNode> stack) {
        while (node != null) {
            stack.push(node);
            node = node.left;
        }
    }
}

Recursive + Binary search, time O(h), space O(1)

考虑bst特性进行二分。其实就是想在bst中找到第一个大于p.val的节点。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        if (root == null || p == null) {
            return null;
        }
        
        if (p.val >= root.val) {
            return inorderSuccessor(root.right, p);
        } else {
            TreeNode left = inorderSuccessor(root.left, p);
            return left != null ? left : root;
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容