二叉树的下一个节点
题目
给定一颗二叉树和其中的一个节点,如何找出中序遍历序列的下一个节点?树中的节点除了有两个分别指向左、右子节点的指针,还有一个指向父节点的指针。
思路
如果一个节点有右子树,那么它的下一个节点就是它的右子树中的最左子节点。也就是说,从右子节点出发一直沿着指向左子节点的指针,我们就能找到它的下一个节点。
如果一个节点没有右子树,如果节点是它父节点的左子节点,那么它的下一个节点就是它的父节点。
如果一个节点既没有右子树,并且它还是它父节点的右子节点,那么这种情形就比较复杂。我们可以沿着指向父节点的指针一直向上遍历,直到找到一个是它父节点的左子节点的节点。
代码
class BinaryTree{
int val;
BinaryTree left;
BinaryTree right;
BinaryTree father;
}
public static getNext(BinaryTree Node){
if(Node==null){
return null;
}
BinaryTree next=new BinaryTree();
if(Node.right!=null)
{
BinaryTree NodeRight= Node.right;
while(NodeRight.left != null)
{
NodeRight=NodeRight.left;
}
next=NodeRight;
}
else if(Node.father != null){
BinaryTree NodeFather=Node.father;
if(NodeFather.left == Node)
{
next=NodeFather;
}
else {
while(NodeFather != null && NodeFather.right == Node){
Node= NodeFather;
NodeFather=NodeFather.father;
}
next=NodeFather;
}
return next;
}
}