And wherein a given binary tree of a node, find the next node in a preorder traversal order and returns.

A need to remember what the topic.

Title Description
Given a binary tree and a node which is, 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.

answer

Next node binary tree:
The traversing rule, when present in the right subtree of the node, the next node traversal sequence for the leftmost node right subtree. However, when the node does not exist right subtree, inorder traversal of the next node in the node must have for the parents. But what is it which generation?
The characteristics traversal sequence, left the parent node must have been visited traversal sequence, so the next node must be the first one on the right parent node of the parent node path.

Inorder traversal results: d-> b-> h-> e- > i-> a-> f-> c-> g
from fits through the results see explanations analysis.

code show as below:

/*
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;
        }
 
        while(pNode.next != null){
            if(pNode.next.left == pNode)
                return pNode.next;
            pNode = pNode.next;
        }
        return null;
    }
}

Guess you like

Origin www.cnblogs.com/dearnotes/p/12563245.html