二叉树的下一个节点
二叉树的下一个结点
http://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e
public TreeLinkNode getNext(TreeLinkNode pNode) {
if (pNode == null)
return null;
if(pNode.right != null){
TreeLinkNode tmp = pNode.right;
while (tmp.left != null)
tmp = tmp.left;
return tmp;
}
else {
//右子树为空,下一个节点在父亲或者祖先节点
//如果此节点为左节点,后继节点为父亲,为右节点则为祖先,为根节点则没有后继
if(pNode.next == null){
//没有父亲,为根节点
return null;
}else {
//有父亲
if(pNode == pNode.next.left){
//为左孩子
return pNode.next;
}
if(pNode == pNode.next.right){
//为右孩子
//找祖先为祖先父亲左孩子的祖先父亲
while (pNode.next != null && pNode.next.next != null && pNode.next != pNode.next.next.left){
pNode = pNode.next;
}
if(pNode.next.next == null){
//没有祖先,则已经遍历完,无后继
return null;
}
return pNode.next.next;//祖先为左孩子
}
}
}
return null;
}
CVTE公司福利 672人发布