二叉树的下一个结点:
根据中序遍历的规则,当结点存在右子树的时候,中序遍历的下一个结点为右子树的最左节点。但是当节点不存在右子树的时候,中序遍历的下一个结点必定为该节点的父辈节点。但是究竟是哪一辈呢?
根据中序遍历特性,左父结点一定已经被中序遍历访问过,所以下一个结点一定是在父节点路径上的第一个右父节点。代码如下:
public TreeLinkNode GetNext(TreeLinkNode pNode){
if(pNode == null) return null;
if(pNode.right != null){
pNode = pNode.right;
while(pNode.left != null)
pNode = pNode.left;
return pNode;
}
while(pNode.next != null){
if(pNode.next.left == pNode)
return pNode.next;
pNode = pNode.next;
}
return null;
}
京公网安备 11010502036488号