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

Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-03-13 22:11:25      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

Construct Binary Tree from Inorder and Postorder Traversal

问题:

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

思路:

  dfs

我的代码:

技术分享
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder == null || inorder.length == 0)  return null;
        if(inorder.length == 1) return new TreeNode(inorder[0]);
        int len = postorder.length;
        int target = postorder[len-1];
        int index = getIndex(inorder, target);
        TreeNode root = new TreeNode(target);
        root.left = buildTree(Arrays.copyOfRange(inorder,0,index),Arrays.copyOfRange(postorder,0,index));
        root.right = buildTree(Arrays.copyOfRange(inorder, index+1, len),Arrays.copyOfRange(postorder, index, len-1));
        return root;
    }
    public int getIndex(int[] inorder, int target)
    {
        for(int i = 0; i < inorder.length; i++)
        {
            if(inorder[i] == target)
                return i;
        }
        return -1;
    }
}
View Code

 

Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4335933.html

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