解法一:中序遍历

通过next不断查找二叉树的根节点,然后再进行迭代or递归的中序遍历。当前一个节点为输入节点时,输出当前节点。
代码太傻,略。

解法二:左右孩子讨论+中序遍历子函数。

  1. 如果当前节点有右孩子,那么下一个结点显然为右孩子中序遍历的第一个元素。

  2. 如果当前节点没有左孩子,就要不断地向上追溯,直到当前节点不再是父节点的右孩子为止,然后输出父节点。

    public class Solution {
     public TreeLinkNode GetNext(TreeLinkNode pNode)
     {
         if(pNode.right!=null) { inorder(pNode.right); return ans;}
         while(pNode.next!=null&&pNode.next.right==pNode) pNode=pNode.next;
         return pNode.next;
     }
    
     TreeLinkNode ans=null;
    
     void inorder(TreeLinkNode pNode){
         if(pNode==null) return;
         inorder(pNode.left);
         if(ans==null) ans=pNode;
         inorder(pNode.right);
         return;
     }
    }

解法三:左右孩子讨论

基本思想和上面差不多,但是对于右孩子的情况,不需要写一个单独的子函数了。

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;
        }
        while(pNode.next!=null&&pNode.next.right==pNode)
            pNode=pNode.next;
        return pNode.next;
    }
}