zoukankan      html  css  js  c++  java
  • [LeetCode] 285. Inorder Successor in BST

    Problem

    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.

    Example 1:

    
    Input: root = [2,1,3], p = 1
    
      2
     / 
    1   3
    
    Output: 2
    

    Example 2:

    
    Input: root = [5,3,6,2,4,null,null,1], p = 6
    
          5
         / 
        3   6
       / 
      2   4
     /   
    1
    
    Output: null
    
    
    

    Solution

    
    class Solution {
        public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
            //successor must be larger then the node itself, so:
            //if p is in root.left, root can be the successor, null cannot be
            //if p is in root.right, root can not be the successor, null can be
            if (root == null) return null;
            if (root.val <= p.val) {
                return inorderSuccessor(root.right, p);
            } else {
                TreeNode leftRes = inorderSuccessor(root.left, p);
                if (leftRes == null) return root;
                return leftRes;
            }
        }
    }
    
    

    原文地址:https://segmentfault.com/a/1190000017066251

  • 相关阅读:
    架构设计
    第七章
    第六章
    第五章
    第四章
    第三章
    第二章
    第一章
    链表中环
    实现链表中的部分翻转
  • 原文地址:https://www.cnblogs.com/lalalagq/p/9985816.html
Copyright © 2011-2022 走看看