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 找到root node,然后通过inorder找到root node的左边全部点和右边全部点:

/**
 * 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) {
        if (preorder == null || preorder.length == 0) {
            return null;
        }
        TreeNode root = new TreeNode (preorder[0]);
        int midIndex = 0;
        for (int i= 0; i < inorder.length; i++) {
            if (inorder[i] == preorder[0]) {
                midIndex = i;
                break;
            }
        }
        root.left = buildTree(Arrays.copyOfRange(preorder, 1, midIndex+1), Arrays.copyOfRange(inorder, 0, midIndex));
        root.right = buildTree(Arrays.copyOfRange(preorder, midIndex+1, preorder.length), Arrays.copyOfRange(inorder, midIndex+1, inorder.length));
        return root;
    }
}

  

 

上一篇:Spark Streaming + Spark SQL 实现配置化ETL流程


下一篇:C#/VB.NET 在Word中添加条码、二维码