zoukankan      html  css  js  c++  java
  • 二叉树查找树中序后继 · Inorder Successor in Binary Search Tree

    [抄题]:

    给一个二叉查找树以及一个节点,求该节点的中序遍历后继,如果没有返回null

    [思维问题]:

    不知道分合算法和后序节点有什么关系:直接return表达式就行了,它自己会终止的。

    [一句话思路]:

    比root大时直接扔右边递归,比root小时 考虑是左边递归还是就是root

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

     

    [一刷]:

    1. 要定义left节点,留着做后续的比较

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

    [总结]:

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    就是树。

    递归表达式,直接出结果。

    [其他解法]:

    太麻烦了

    [Follow Up]:

    [LC给出的题目变变变]:

    锁着了

    public class Solution {
        /*
         * @param root: The root of the BST.
         * @param p: You need find the successor node of p.
         * @return: Successor of p.
         */
        public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
            if (root == null || p == null) {
                return null;
            }
            
            if (p.val >= root.val) {
                return inorderSuccessor(root.right, p);
            }
            else {
                TreeNode left = inorderSuccessor(root.left, p);
                return (left != null) ? left : root;
            }
        }
    }
    View Code
  • 相关阅读:
    内存分析利器purify简介
    ldd 的一个安全问题
    Purify检测的代码错误类型
    Purify命令大全
    用GDB调试程序(三)
    寒假Day5:蓝桥杯模拟赛
    寒假Day1:莫队算法+暴力分块
    HDU4578Transformation线段树的加、乘、变、次方操作
    二叉树的相关知识点
    CodeForces 841BGodsend思维
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8379538.html
Copyright © 2011-2022 走看看