/*
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;
        // 1. 节点有右子树。
        if(pNode.right != null) {
            TreeLinkNode pp = pNode;
            TreeLinkNode cur = pNode.right;
            while (cur.left != null) {
                cur = cur.left;
            }
            return cur;
        } // 2. 节点无右子树,并且是其父节点的左子树
        else if(pNode.next != null && pNode.next.left == pNode) {
            return pNode.next;
        } else {
            // 3. 节点无右子树,沿着指向父节点的指针往上遍历,直到找到一个是它父节点的左子节点的节点。
            if(pNode.next == null) return null;
            TreeLinkNode father = pNode.next;
            while (father.next != null && father.next.left != father) {
                father = father.next;
            }
            return father.next;
        }
    }
}