• 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.

    本来想先对inorder array做预处理存上val对应的index,结果发现 val可能有duplicates。

     1 /**duplicates
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public TreeNode buildTree(int[] preorder, int[] inorder) {
    12         // IMPORTANT: Please reset any member data you declared, as
    13         // the same Solution instance will be reused for each test case.
    14         return preorder_inorder(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    15     }
    16     public TreeNode preorder_inorder(int[] pre, int ps, int pe, int[] in, int is, int ie){
    17         if(ps > pe || is > ie) return null;
    18         TreeNode root = new TreeNode(pre[ps]);
    19         int ind = 0;
    20         for(int i = is; i <= ie; i++)
    21             if(in[i] == root.val){
    22                 ind = i;
    23                 break;
    24         }
    25         int len = ind - is;
    26         root.left = preorder_inorder(pre, ps + 1, ps + len, in, is, ind - 1);
    27         root.right = preorder_inorder(pre, ps + 1 + len, pe, in, ind + 1, ie);
    28         return root;
    29     }
    30 }
  • 相关阅读:
    结构-行为-样式-有趣的函数
    结构-行为-样式-angularJs笔记
    Js-Html 前端系列--页面撑开头尾
    Java 实现下载
    Js-Html 前端系列--Ajax
    Js-Html 前端系列--checkbox
    Nutz中过滤特殊字符
    NUTZ中处理系统未捕获异常
    Thymeleaf 笔记
    Json 使用小结
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3426342.html
Copyright © 2020-2023  润新知