/* 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.left == null && pNode.right == null && pNode.next == null) return null; if(pNode.left == null && pNode.right == null){ // 叶节点 if(pNode.next.left == pNode){ // 左叶节点 return pNode.next; // 返回父节点 }else { // 右叶节点 while(pNode != null){ if(pNode.next != null && pNode.next.left == pNode) { return pNode.next; } pNode = pNode.next; } } }else{ // 非叶节点 if(pNode.right != null){ // 存在右子树 pNode = pNode.right; while(pNode.left!=null){ pNode = pNode.left; } return pNode; }else { return pNode.next; } } return null; } }
画图之后分情况讨论:
1. 如果只有一个输入的是一个孤立点,那么直接返回null;
2. 如果输入的是一个非叶子结点:
2.1: 如果存在右子树,那么找到右子树中最左的结点返回
2.2:如果不存在右子树,则返回null,因为当前结点就是最后一个结点。
3. 如果是叶子结点:
3.1:如果该叶子节点是父节点的左节点,则直接返回父节点;
3.2:如果该叶子结点是父节点的右结点,则循环向上寻找到某个结点是其父节点的左节点,并且返回它的父节点;如果找不到则返回null。