二叉树的下一节点
二叉树的下一个结点
http://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e
分情况:
- 当前节点有右子树,那下一节点肯定是右子树的最左节点
- 当前节点没有右子树
- 当前节点是父节点的左节点,下一个是父节点
- 当前节点是父节点的右节点,下一个是顺着父节点遍历上去的父节点
/* public class TreeLinkNode { int val; TreeLinkNode left = null; TreeLinkNode right = null; TreeLinkNode next = null; TreeLinkNode(int val) { this.val = val; } } */ public class Solution { 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; }else{ //当前节点没有右子树 while(pNode.next != null){ if(pNode.next.left == pNode){ //当前节点是父节点的左子树 return pNode.next; }else{ //当前节点是父节点的右子树 pNode = pNode.next; } } } return null; } }