题目:给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点而且返回。注意,树中的结点不只包含左右子结点,同时包含指向父结点的指针。spa
分析:
根据中序遍历的特色,要找到一个节点的下一个节点无非就是三种状况:
一、有右子树,这时只须要把其右孩子做为下一个遍历的(并非要找的)节点,而后沿着该节点的左子树(若是有的话)出发,直到遇到叶子节点,那么该叶子节点就是其下一个要找的节点;
二、没有右子树,则判断该节点是不是其父节点的左孩子,若是是则其下一个要找的节点是其父节点;
三、若是不是其父节点的左孩子,则把其父节点做为下一个遍历的节点,向上回溯,直到找到节点没有父节点或者节点是其父节点的左孩子为止。
综合这三种状况就能够找到二叉树中任意一个节点的下一个节点。指针
代码以下:code
public class FindNextNode { public BinaryTreeNode getNextNode(BinaryTreeNode pNode){ if(pNode==null){ return null; } //若是该节点有右节点 if(pNode.getRightNode()!=null){ BinaryTreeNode tempNode=pNode.getRightNode(); while(tempNode.getLeftNode()!=null){ tempNode=tempNode.getLeftNode(); } return tempNode; } //若是没有右节点,是其父节点的左子节点 if(pNode.getFatherNode()==null){ return null; } if(pNode.getFatherNode().getLeftNode()==pNode){ return pNode.getFatherNode(); } //若是没有右节点,是其父节点的右子节点,一直向上找父节点直到没有父节点 if(pNode.getFatherNode()==null){ return null; } if(pNode.getFatherNode().getRightNode()==pNode){ BinaryTreeNode tempNode=pNode.getFatherNode(); while(tempNode.getFatherNode()==null){ tempNode=tempNode.getFatherNode(); } return tempNode; } return null; } }