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

    Problem 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.


    There are just two cases:

    1. The easier one: p has right subtree, then its successor is just the leftmost child of its right subtree;
    2. The harder one: p has no right subtree, then a traversal is needed to find its successor.

    Traversal: we start from the root, each time we see a node with val larger than p -> val, we know this node may be p's successor. So we record it in suc. Then we try to move to the next level of the tree: if p -> val > root -> val, which means p is in the right subtree, then its successor is also in the right subtree, so we update root = root -> right; if p -> val < root -> val, we update root = root -> left similarly; once we find p -> val == root -> val, we know we've reached at p and the current sucis just its successor.

    The code is as follows. You may try some examples to see how it works :-)

     1 class Solution {
     2 public:
     3     TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
     4         if (p -> right) return leftMost(p -> right);
     5         TreeNode* suc = NULL;
     6         while (root) {
     7             if (p -> val < root -> val) {
     8                 suc = root;
     9                 root = root -> left;
    10             }
    11             else if (p -> val > root -> val)
    12                 root = root -> right; 
    13             else break;
    14         }
    15         return suc;
    16     }
    17 private:
    18     TreeNode* leftMost(TreeNode* node) {
    19         while (node -> left) node = node -> left;
    20         return node;
    21     }
    22 };
  • 相关阅读:
    锻炼记录
    PHP学习笔记
    返回一个整数数组中最大子数组的和(2)
    四则运算的在线答题(判断对错,记录错题)
    返回一个二维整数数组的最大子数组的和
    返回一个整数数组中最大子数组的和
    程序2:支持真分数的四则运算
    程序1:四则运算
    四则运算3.0版本
    返回二维数组子数组和最大值
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4829200.html
Copyright © 2011-2022 走看看