zoukankan      html  css  js  c++  java
  • LeetCode -- Construct Binary Tree from Preorder and Inorder

    Question:

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

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

    Analysis:

    给出一棵树的前序遍历和中序遍历,构建这棵二叉树。 

    注意: 你可以假设树中不存在重复的关键码。
     
    思路:
    前序遍历和中序遍历肯定是可以唯一确定一棵二叉树的。
     前序遍历的第一个节点肯定是根节点,得到根节点后再到中序遍历中,可以很容易的找出左子树和右子树,然后这样递归的找根节点,确立左子树、右子树……
     
    Answer:
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            return buildTreeHelper(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
        }
        
        public TreeNode buildTreeHelper(int[] preorder, int[] inorder, int pre1, int pre2, int in1, int in2) {
            if(pre1 > pre2)
                return null;
            int pivot = pre1;
            int i = in1;
            for(; i<in2; i++) {
                if(preorder[pivot] == inorder[i])
                    break;
            }
            TreeNode t = new TreeNode(preorder[pivot]);
            int len = i - in1;
            t.left = buildTreeHelper(preorder, inorder, pivot+1, pivot+len, in1, i-1);
            t.right = buildTreeHelper(preorder, inorder, pivot+len+1, pre2, i+1, in2);
            return t;
        }
        
    }
  • 相关阅读:
    斜率优化dp学习
    拓扑排序
    P2486 [SDOI2011]染色 区间合并+树链剖分(加深对线段树的理解)
    网络流24题!!!!
    费用流板子
    网络流dinic板子
    小花梨的数组
    C. 小花梨判连通
    splay树
    hdu4467 graph
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5235775.html
Copyright © 2011-2022 走看看