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;
        }
        
    }
  • 相关阅读:
    部分网络加载预训练模型代码实现
    数据不平衡处理方法
    面试题目汇总
    多线程和多进程
    数据结构知识点总结
    GBDT和XGBoost的区别
    GBDT和随机森林的区别
    机器学习-特征处理
    一篇写得很好的关于lct的博客
    Count and Say 2014/10/23
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5235775.html
Copyright © 2011-2022 走看看