美文网首页
[LeetCode 285] Inorder Successor

[LeetCode 285] Inorder Successor

作者: 灰睛眼蓝 | 来源:发表于2019-06-04 14:04 被阅读0次

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

The successor of a node p is the node with the smallest key greater than p.val.

Example 1:

image

Input: root = [2,1,3], p = 1
Output: 2
Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.
==================================================================================

Example 2:

image

Input: root = [5,3,6,2,4,null,null,1], p = 6
Output: null
Explanation: There is no in-order successor of the current node, so the answer is null.

Note:

  1. If the given node has no in-order successor in the tree, return null.
  2. It's guaranteed that the values of the tree are unique.

Solution : 中序遍历

1。中序遍历,过程中记录prev node, 同时检查prev node是否与给定的p node值相同,如果相同,那么当前的节点就是inorder successor.

/**
 * 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) {
        TreeNode[] successor = {null};
        TreeNode[] prev = {null};
        
        inorderSuccessorHelper (root, p, successor, prev);
        
        return successor[0];
    }
    
    public boolean inorderSuccessorHelper (TreeNode root, TreeNode p, TreeNode[] successor, TreeNode[] prev) {
        if (root == null) {
            return false;
        }
        
        // in-prder: first left subtree and find the prev node
        if (inorderSuccessorHelper (root.left, p, successor, prev))
            return true;
        
        // check if prev is equal to p. if yes, then current node is the successor;
        // if not, update the prev node
        if (prev[0] != null && prev[0].val == p.val) {
            successor[0] = root;
            // prev[0] = root;
            // System.out.println (successor[0].val);
            return true;
        }
        
        prev[0] = root;
        
        if (inorderSuccessorHelper (root.right, p, successor, prev))
            return true;
        
        return false;
    }
}

相关文章

网友评论

      本文标题:[LeetCode 285] Inorder Successor

      本文链接:https://www.haomeiwen.com/subject/kqmvbqtx.html