zoukankan      html  css  js  c++  java
  • construct-binary-tree-from-preorder-and-inorder-traversal

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

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

    package com.cn.cya.constructbinarytreefrompreorderandinordertraversal;
    class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode(int x) { val = x; }
     }
    public class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if(preorder==null||preorder.length==0||inorder==null||inorder.length==0||preorder.length!=inorder.length)
                return null;
        
            
            return build_Tree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
        }
        public TreeNode buildTree(int[] preorder,int prestar,int preend,int[] inorder,int instar,int inend){
            if(prestar>preend||instar>inend)return null;
            int root_val=preorder[prestar];
            TreeNode root=new TreeNode(root_val);
            int index=instar;//preorder中第一个元素在中序遍历中的位置
            for (;index < inend&&inorder[index]!=root_val; index++) {    
            }
            root.left=buildTree(preorder,prestar+1, prestar+index-instar, inorder,instar,index-1);
            root.right=buildTree(preorder,prestar+index-instar+1, preend, inorder,index+1,inend);
            return root;
        }
      
    }
  • 相关阅读:
    剑指 Offer 25. 合并两个排序的链表
    53. 最大子序和 动态规划
    121. 买卖股票的最佳时机
    20. 有效的括号
    centos7 常用操作
    树莓派
    golang 学习笔记
    并发 线程 进程
    连接内网问题
    Lamp 高并发优化
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/5517830.html
Copyright © 2011-2022 走看看