博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
285. Inorder Successor in BST - Medium
阅读量:7140 次
发布时间:2019-06-28

本文共 1951 字,大约阅读时间需要 6 分钟。

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   3Output: 2

Example 2:

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

 

M1: recursive

time: O(n), space: O(height)

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {        if(root == null) {            return null;        }        if(p.val >= root.val) {            return inorderSuccessor(root.right, p);        } else {            TreeNode left = inorderSuccessor(root.left, p);            if(left != null) {                return left;            } else {                return root;            }        }    }}

 

M2: iterative

分两种情况考虑:p有无右子节点

如果p有右子节点,返回右子树的最左子节点;如果没有,从root开始按inorder遍历找successor

time: O(n), space: O(1)

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {        if(root == null) {            return null;        }                if(p.right != null) {            TreeNode cur = p.right;            while(cur.left != null) {                cur = cur.left;            }            return cur;        }                else {            TreeNode s = root, t = null;            while(s.val != p.val) {                if(p.val <= s.val) {                    t = s;                    s = s.left;                } else {                    s = s.right;                }            }            return t;        }    }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10204178.html

你可能感兴趣的文章
公共DNS服务器整理
查看>>
面试官问我:什么是JavaScript闭包,我该如何回答
查看>>
electronjs 入门_2019年2月14日
查看>>
vue源码分析系列之入口文件分析
查看>>
php 验证格式的函数总结
查看>>
微服务架构组件分析,看这篇就够了
查看>>
Java多线程进阶(二九)—— J.U.C之collections框架:ConcurrentLinkedQueue
查看>>
数据仓库之ETL实战
查看>>
MVC 框架中的路由器(Router)是如何跑起来的
查看>>
electron跳坑指南 1(electron的安装)
查看>>
Elasticsearch 的一些常见疑问(持续更新中)
查看>>
聚焦区块链应用,SegmentFault 黑客马拉松引爆珠三角
查看>>
mongoose的date类型和timestamps的使用
查看>>
获取小程序二维码
查看>>
对Java多线程的一些理解
查看>>
git仓库完整迁移
查看>>
javascript闭包
查看>>
聊聊Dubbo - Dubbo可扩展机制实战
查看>>
阿里最年轻合伙人胡喜:骨子里没点技术理想主义干不来自主研发
查看>>
JSP第六篇【自定义标签之传统标签】
查看>>