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

105 Construct Binary Tree From Preorder and Inorder Traversal

时间:2015-05-19 10:09:22      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null || preorder.length != inorder.length || preorder.length == 0) {
            return null;
        }
        
        int rootVal = preorder[0];
        int mid = 0;
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == rootVal) {
                mid = i;
                break;
            }
        }
        
        int[] leftPre = Arrays.copyOfRange(preorder, 1, mid + 1);
        int[] leftIn = Arrays.copyOfRange(inorder, 0, mid);
        int[] rightPre = Arrays.copyOfRange(preorder, mid + 1, preorder.length);
        int[] rightIn = Arrays.copyOfRange(inorder, mid + 1, inorder.length);
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(leftPre, leftIn);
        root.right = buildTree(rightPre, rightIn);
        return root;
    }
}

参考:http://www.cnblogs.com/huntfor/p/3883517.html

根据前序序列和中序序列构建树。递归。

105 Construct Binary Tree From Preorder and Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/77rousongpai/p/4513583.html

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