• 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;
        }
      
    }
  • 相关阅读:
    运算符的优先级
    运算符
    值类型与引用类型的区别
    进制转换
    Java总结第二期
    Java总结第一期
    库存管理系统
    MyBank后感
    day72
    day71
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/5517830.html
Copyright © 2020-2023  润新知