LeetCode Question Bank Answers and Analysis - #106. Construct Binary Tree from Inorder and Postorder Traversal Sequence ConstructBinaryTreeFromInorderAndPostorderTraversal

Given the in-order traversal and post-order traversal of a tree, construct a binary tree based on this.

Note:
You can assume that there are no duplicate elements in the tree.

For example, given

Inorder traversal = [9,3,15,20,7]
Postorder Traversal = [9,15,7,20,3]

Returns the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

Personal thoughts:

The last element of the post-order traversal sequence must be the root node of the tree, so starting from this, find the element in the in-order traversal sequence, and all its left elements are the nodes of the left subtree with this element as the root node. All elements on the right are the nodes of the right subtree with this element as the root node, and the two sides can be divided into two new arrays, the left subtree and the inorder traversal subsequence of the right subtree. At the same time, the nodes after the root node in the post-order traversal sequence all traverse the left subtree node first before traversing the right subtree node. Therefore, according to the number of left subtree nodes in the in-order traversal sequence, find all the nodes belonging to the left subtree. and the elements of the right subtree, and split into two new postorder traversal subsequence arrays. Then use recursion to process the post-order and in-order sequences of the left and right subtrees respectively. If the sequence is empty, return null. If the sequence has only one value, it can be judged as a leaf node and return the current node. Finally, a complete binary tree can be obtained.

Code (JavaScript):

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} inorder
 * aramparam {number []} postorder
 * @return {TreeNode}
 */
var buildTree = function (inorder, mailorder) {
    var l = mailorder.length;
    if(l==0){
        return null;
    }
    var root = new TreeNode (mail order [l-1]);    
    if(l==1){
        return root;
    }
    var pos=0;
    for(pos=0;pos<l;pos++){
        if(inorder[pos]==postorder[l-1]){
            break;
        }
    }
    var Lpostorder=new Array(pos);
    var Linorder=new Array(pos);
    var Rpostorder=new Array(l-pos-1);
    var Rinorder=new Array(l-pos-1);
    for(var i=0;i<pos;i++){
        Linorder[i]=inorder[i+1];
        Mail order [i] = mail order [i];
    }
    root.left=buildTree(Linorder,Lpostorder);
    for(var i=0;i<l-pos-1;i++){
        Rinorder[i]=inorder[i+pos+1];
        Rpostorder [i] = mail order [i + pos];
    }
    root.right=buildTree(Rinorder,Rpostorder);
    return root;
    
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324609213&siteId=291194637