LeetCode-Construct Binary Tree from Preorder and Inorder Traversal

题目:

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

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

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

 

实现:

  • 递归方式,根据二叉树中序遍历和前续遍历,创建二叉树。中序遍历: 左-根-右,前续遍历: 根-左-右, 所以可以通过前续遍历的第一个节点找到根节点,并生成根节点, 因为二叉树没有重复节点, 就 可以在中序遍历数据中找到根节点,再分成左右两个子树,递归执行下去,遍历完所有节点。 通过preorder获取根节点, 通过inorder生成左右子树,查找节点在中序遍历数据组里位置,java可以通过HashMap实现。 
  • 不使用map情况下   时间复杂度 O(N^2)    , 使用map查找O(N)      
/** java
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        Map<Integer, Integer> treemap = new HashMap <>();
        for (int i=0; i<inorder.length; i++){
            treemap.put(inorder[i], i);
        }
        
     
        AtomicInteger rootindex = new AtomicInteger(0); 
        return helper(preorder, inorder, 0, inorder.length -1, rootindex, treemap);
    }
    
     public TreeNode helper(int[] preorder, int[] inoder, int left, int right, AtomicInteger index, Map<Integer, Integer> treemap) {
   
        if (left > right){
            return null;
        }
        //new node, set root
        int val = preorder[index.intValue()];
        TreeNode node = new TreeNode(val);
        index 
       
        //search inorder 
        int root = treemap.get(val);
        
        //left substree
        node.left = helper(preorder, inoder, left, root-1, index, treemap);
        //right substree
        node.right = helper(preorder, inoder, root+1, right, index, treemap);
    
        return node ;
        
    }
}

参考及引用:

techiedelight-construct-binary-tree-from-inorder-preorder-traversal

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注