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

【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解题报告

时间:2014-11-27 12:50:15      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:二叉树   中序遍历   先序遍历   dfs   

【原题】

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

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

【解析】

题意:根据二叉树先序遍历和中序遍历的结果,构造二叉树。跟 根据中序遍历和后序遍历结果构造二叉树 类似。

先序遍历:root - left - right,中序遍历:left - root - right。

不同的是,先序遍历的第一个元素就是根节点。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int[] preorder;
    int[] inorder;
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length < 1 || inorder.length < 1) return null;
        this.preorder = preorder;
        this.inorder = inorder;
        return getRoot(0, inorder.length - 1, 0);
    }
    
    // sub-tree range form begin to end in inorder[]
    // rootpos refer the root postion in preorder[]
    public TreeNode getRoot(int begin, int end, int rootpos) {
        if (begin > end) return null;
        TreeNode root = new TreeNode(preorder[rootpos]);
        int i;
        for (i = begin; i <= end; i++) {
            if (inorder[i] == preorder[rootpos]) break;
        }
        // left part length: i - begin, right part length: end - i
        root.left = getRoot(begin, i - 1, rootpos + 1);
        root.right = getRoot(i + 1, end, rootpos + 1 + (i - begin));
        return root;
    }
}


【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解题报告

标签:二叉树   中序遍历   先序遍历   dfs   

原文地址:http://blog.csdn.net/ljiabin/article/details/41542969

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