• 【LeetCode】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.

    public class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if(preorder.length==0||inorder.length==0)
                return null;
            return BuildTreeNode(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
            
            
            
            
        }
    
        private TreeNode BuildTreeNode(int[] preorder, int prestart, int preend, int[] inorder,
                int instart, int inend) {
            if(prestart>preend||instart>inend)
                return null;
            int temp = preorder[prestart];
            TreeNode root = new TreeNode(temp);
            int leftlength=0;
            
            for(int i=instart;i<=inend;i++){
                if(inorder[i]!=temp)
                    leftlength++;
                else if(inorder[i]==temp)
                    break;
            }
            root.left=BuildTreeNode(preorder, prestart+1, prestart+leftlength, inorder, instart,instart+leftlength-1);
            root.right=BuildTreeNode(preorder,prestart+leftlength+1,preend,inorder,instart+leftlength+1,inend);
            return root;
        }
    }
  • 相关阅读:
    iOS testFlight的使用
    Java读书笔记
    Vim编辑器
    seleniumRC测试用例——登录
    自动化测试工具——selenium
    《Oracle从入门到精通》
    WEB服务器相关知识摘录
    oracle表空间与分区表
    Linux 常用命令
    Linux 常见问题
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3722606.html
Copyright © 2020-2023  润新知