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

    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

    思路:

      dfs

    我的代码:

    public class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if(inorder == null || inorder.length == 0)  return null;
            if(inorder.length == 1) return new TreeNode(inorder[0]);
            int len = preorder.length;
            int target = preorder[0];
            int index = getIndex(inorder, target);
            TreeNode root = new TreeNode(target);
            root.left = buildTree(Arrays.copyOfRange(preorder,1,index + 1),Arrays.copyOfRange(inorder,0,index));
            root.right = buildTree(Arrays.copyOfRange(preorder, index + 1, len),Arrays.copyOfRange(inorder, index+1, len));
            return root;
        }
        public int getIndex(int[] inorder, int target)
        {
            for(int i = 0; i < inorder.length; i++)
            {
                if(inorder[i] == target)
                    return i;
            }
            return -1;
        }
    }
    View Code
  • 相关阅读:
    202002知识点
    爬取思想流程
    测试
    运维
    设计模式重温
    ?March2020疑问点
    最方便简洁的设置Sublime编辑预览MarkDown
    rime中州韵输入法安装及配置
    Deepin更新Sublime并取消更新提示
    关于在线教学软件一些发现和思考
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4337358.html
Copyright © 2011-2022 走看看