码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Construct Binary Tree from Preorder and Inorder Traversal

时间:2016-01-10 11:44:45      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

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

思路:

递归,preorder的第一个元素必然是根节点

package treetraversal;

public class ConstructBinaryTreeFromPreorderAndInorderTraversal {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return construct(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }
    
    private TreeNode construct(int[] preorder, int pstart, int pend, int[] inorder, int istart, int iend) {
        if (pstart > pend || istart > iend) return null;
        int rootVal = preorder[pstart];
        int index = -1;
        for (int i = istart; i <= iend; ++i) {
            if (inorder[i] == rootVal) {
                index = i;
                break;
            }
        }
        
        TreeNode root = new TreeNode(rootVal);        
        root.left = construct(preorder, pstart + 1, index - istart + pstart, inorder, istart, index - 1);
        root.right = construct(preorder, index - istart + pstart + 1, pend, inorder, index + 1, iend);
        return root;
    }
    
}

 

LeetCode - Construct Binary Tree from Preorder and Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5118067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!