题目来源:剑指offer
给定一个二叉树和其中一个节点,如何找出中序遍历序列的下一个节点?书中的节点除了有两个分别指向左右的指针,还有一个指向父节点的指针
思路:见程序(剑指offer)
/**
* 1.如果该节点的右孩子不为空,则下一个节点位右孩子的最左子孙
* 2.如果该节点的有孩子为空,并且为父亲的左孩子,则中序遍历的下一个节点为父亲
* 3.如果该节点的右孩子节点为空,并且是父亲节点的有孩子,该情况中序遍历的下一个节点是向上寻找第一个节点是其父节点的左节点的节点
* @author ld851
*/
public class J_shuDxiaJiedian {
public TreeNode getNext(TreeNode node){
if (node==null)
return null;
TreeNode n=new TreeNode();//
if (node.right!=null){
n=node.right;
while (n.left!=null)
n=n.left;
//return n;
}
else if (node.parent!=null){
TreeNode pa=node.parent;
TreeNode current=node;
while(pa!=null&¤t==pa.right){//如果是pa为空退出条件也就是,没有上边没有节点市父节点的做节,返回pa为空
current=pa;
pa=pa.parent;
}
n=pa;
}
return n
}
}