zoukankan      html  css  js  c++  java
  • *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.

    解法一:俺自个儿的方法,居然跑了16ms。。。妈蛋!

    public class Solution {
        public TreeNode inorderSuccessor(TreeNode root, TreeNode p) 
        {
            ArrayList<TreeNode> res = inOrderTrav(root);
            for(int i=0;i<res.size()-1;i++)
            {
                if(p==res.get(i))
                return res.get(i+1);
            }
            
            return null;
            
        }
        
        public ArrayList<TreeNode> inOrderTrav(TreeNode root)
        {
            LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
            ArrayList<TreeNode> res = new ArrayList<TreeNode>();
            if(root==null) return res;
            while(root!=null||!stack.isEmpty())
            {
                if(root!=null)
                {
                    stack.push(root);
                    root = root.left;
                }
                else
                {
                    root = stack.pop();
                    res.add(root);
                    root = root.right;
                }
            }
            return res;
        }
    }

    解法二:

    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode succ = null;
        while (root != null) {
            if (p.val < root.val) {
                succ = root;
                root = root.left;
            }
            else
                root = root.right;
        }
        return succ;
    }

    reference:https://leetcode.com/discuss/61105/java-python-solution-o-h-time-and-o-1-space-iterative

  • 相关阅读:
    1026. 程序运行时间(15)
    C语言字符串/数组去重
    1025. 反转链表 (25)
    1024. 科学计数法 (20)
    1023. 组个最小数 (20)
    1022. D进制的A+B (20)
    1021. 个位数统计 (15)
    1020. 月饼 (25)
    前端001/正则表达式
    SSM001/构建maven多模块项目
  • 原文地址:https://www.cnblogs.com/hygeia/p/5104279.html
Copyright © 2011-2022 走看看