LeetCode -- Construct Binary Tree from Preorder and Inorder

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode -- Construct Binary Tree from Preorder and Inorder相关的知识,希望对你有一定的参考价值。

Question:

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

 

Analysis:

给出一棵树的前序遍历和中序遍历,构建这棵二叉树。 

注意: 你可以假设树中不存在重复的关键码。
 
思路:
前序遍历和中序遍历肯定是可以唯一确定一棵二叉树的。
 前序遍历的第一个节点肯定是根节点,得到根节点后再到中序遍历中,可以很容易的找出左子树和右子树,然后这样递归的找根节点,确立左子树、右子树……
 
Answer:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeHelper(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }
    
    public TreeNode buildTreeHelper(int[] preorder, int[] inorder, int pre1, int pre2, int in1, int in2) {
        if(pre1 > pre2)
            return null;
        int pivot = pre1;
        int i = in1;
        for(; i<in2; i++) {
            if(preorder[pivot] == inorder[i])
                break;
        }
        TreeNode t = new TreeNode(preorder[pivot]);
        int len = i - in1;
        t.left = buildTreeHelper(preorder, inorder, pivot+1, pivot+len, in1, i-1);
        t.right = buildTreeHelper(preorder, inorder, pivot+len+1, pre2, i+1, in2);
        return t;
    }
    
}

 

以上是关于LeetCode -- Construct Binary Tree from Preorder and Inorder的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode&Python] Problem 427. Construct Quad Tree

LeetCode Construct String from Binary Tree

LeetCode:492. Construct the Rectangle

492. Construct the Rectangle(LeetCode)

leetcode-492-Construct the Rectangle

[LeetCode&Python] Problem 606. Construct String from Binary Tree