Next node binary tree 57-

And wherein a given binary tree of a node, find the next node in a preorder traversal order and returns. Note that the node in the tree contains not only the left and right child nodes, the parent node contains a pointer pointing to.

  1. If a node has a right child, then it's the next node is the most left child of its right sub-tree. In other words, starting from the right child node has been along the pointer to the left child node, we can find the next node.
  2. If there is no right subtree, it can be divided into two cases
    • If the node is left child of its parent node, then it's the next node is its parent.
    • If a node is neither the right child, and it is the right child of the parent node, then the need to facilitate the way up along a pointer to the parent node until it finds a node is left child of its parent.
/*function TreeLinkNode(x){
    this.val = x;
    this.left = null;
    this.right = null;
    this.next = null;
}*/
function GetNext(pNode)
{
    // write code here
    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) {
        if(pNode == pNode.next.left) {
            return pNode.next;
        }
        pNode = pNode.next;
    }
    return null
}
Published 80 original articles · won praise 0 · Views 1956

Guess you like

Origin blog.csdn.net/weixin_43655631/article/details/104098276