LeetCode 剑指 Offer II 053. 二叉搜索树中的中序后继
题目描述
给定一棵二叉搜索树和其中的一个节点 p ,找到该节点在树中的中序后继。如果节点没有中序后继,请返回 null 。节点 p 的后继是值比 p.val 大的节点中键值最小的节点,即按中序遍历的顺序节点 p 的下一个节点。
示例 1:
输入:root = [2,1,3], p = 1
输出:2
解释:这里 1 的中序后继是 2。请注意 p 和返回值都应是 TreeNode 类型。
LeetCode 剑指 Offer II 053. 二叉搜索树中的中序后继
提示:
树中节点的数目在范围 [1, 104] 内。
-105 <= Node.val <= 105
树中各节点的值均保证唯一。
一、解题关键词
二、解题报告
1.思路分析
2.时间复杂度
3.代码示例
/**
* 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) {
TreeNode ans = null;
while(null != root){
if(root.val > p.val){
ans = root;
root = root.left;
}else{
root = root.right;
}
}
return ans;
}
}
方法二
TreeNode ans;
boolean isp;
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
dfs(root, p);
return ans;
}
void dfs(TreeNode root, TreeNode p) {
if (root == null) return;
dfs(root.left, p);
if (isp && ans == null) {
ans = root;
return;
}
if (p.val == root.val) {
isp = true;
}
dfs(root.right, p);
}
2.知识点