题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
思路分析
主要分3中情况:
(1)当前节点有右子树:返回当前节点右子树最左结点;
(2)当前节点无右子树、是父节点的左子树中的结点:返回父节点;
(3)当前节点无右子树、是父节点的右子树中的结点:找到一个节点,该结点的父节点的左直接左孩子是该结点,返回父节点。
参考代码
public TreeLinkNode GetNext(TreeLinkNode root)
{
if(root == null)return root;
//1. 该结点有右子树
if(root.right != null){
TreeLinkNode node = root.right;
//返回右子树最左结点
while(node.left != null){
node = node.left;
}
return node;
}
//2. 无右子树,况且是父节点的左子树
else if(root.next != null && root.next.left == root){
//直接返回父节点
return root.next;
}
//3.无右子树,况且是父节点的右子树
else if(root.next != null && root.next.right == root){
//找到某个节点,该结点是父节点的左子树结点,返回父节点
while(root.next != null && root.next.right == root){
root = root.next;
}
//找到后直接返回
if(root.next != null)return root.next;
}
//未找到,返回null
return null;
}
注意:
if 条件语句中的next要判空