题目
给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点。
注意:
如果给定的节点是中序遍历序列的最后一个,则返回空节点;
二叉树一定不为空,且给定的节点一定不是空节点;
样例:
假定二叉树是:[2, 1, 3, null, null, null, null], 给出的是值等于2的节点。
则应返回值等于3的节点。
算法
分情况讨论
1、如果当前节点存在右子树,那么右子树的最左侧节就是当前节点的后继节点。(例如F的后继节点是H)
2、如果不存在右子树,就需要沿着father域向上查找,找到第一个是其father左儿子的节点。(例如D的后继节点,则第一个满足是其father左儿子的节点是F,则F的father就是D的后继)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode father;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode p) {
if(p == null) return null;
//如果当前节点右子树不为空,则当前节点的后继节点为右子树第一个左节点
if(p.right != null){
p = p.right;
while(p.left != null) p = p.left;
return p;
}
//右子树不存在 只有左子树
while(p.father != null){
if(p == p.father.left) return p.father;
p = p.father;
}
return null;
}
}