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

    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:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public class Result{
            TreeNode resNode;
            boolean foundP;
            boolean foundRes;
            public Result(){
                resNode = null;
                foundP = false;
                foundRes = false;
            }
        }
        public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
            Result res = new Result();
            searchTree(root,p,res);
            return res.resNode;
        }
        
        public void searchTree(TreeNode cur, TreeNode p, Result res){
            if (cur==null){
                return;
            }
            
            searchTree(cur.left,p,res);
            if (res.foundP && res.foundRes) return;
            if (res.foundP){
                res.resNode = cur;
                res.foundRes = true;
                return;
            }
            if (cur == p){
                res.foundP = true;
            }
            searchTree(cur.right,p,res);
        }
    }
  • 相关阅读:
    四则运算测试脚本运行情况
    AAA
    (2015秋) 软工作业成绩公布(12月26号更新)
    判断闰年的Java算法
    B
    A
    Where Amazing Happens
    安利一发资料站
    C
    B
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5839211.html
Copyright © 2011-2022 走看看