zoukankan      html  css  js  c++  java
  • leetcode105: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.

    解题思路分析:

    前序遍历首先遍历根节点,然后依次遍历左右子树

    中序遍历首先遍历左子树,然后遍历根结点,最后遍历右子树

    根据二者的特点,前序遍历的首节点就是根结点,然后在中序序列中找出该结点位置(index),则该结点之前的为左子树结点,该节点之后为右子树结点;

    同样对于前序序列,首结点之后的index个结点为左子树结点,剩余的节点为右子树结点;

    最后,递归建立子树即可。

    java代码:

     1 public class Solution {
     2     public TreeNode buildTree(int[] preorder, int[] inorder) {
     3         if(preorder == null || preorder.length == 0){
     4             return null;
     5         }
     6         
     7         int flag = preorder[0];
     8         TreeNode root = new TreeNode(flag);
     9         int i = 0;
    10         for(i=0; i<inorder.length; i++){
    11             if(flag == inorder[i]){
    12                 break;
    13             }
    14         }
    15         
    16         int[] pre_left, pre_right, in_left, in_right;
    17         pre_left = new int[i];
    18         for(int j=1; j<=i;j++){
    19             pre_left[j-1] = preorder[j];
    20         }
    21         pre_right = new int[preorder.length-i-1];
    22         for(int j=i+1; j<preorder.length;j++){
    23             pre_right[j-i-1] = preorder[j];
    24         }
    25         
    26         in_left = new int[i];
    27         for(int j=0;j<i;j++){
    28             in_left[j] = inorder[j];
    29         }
    30         in_right = new int[inorder.length-i-1];
    31         for(int j=i+1; j<inorder.length; j++){
    32             in_right[j-i-1] = inorder[j];
    33         }
    34         root.left = buildTree(pre_left,in_left);
    35         root.right = buildTree(pre_right,in_right);
    36         
    37         
    38         
    39         return root;
    40         
    41     }
    42     
    43    
    44 }
  • 相关阅读:
    第5课.异步通知
    第4课.poll机制
    第3课.Linux异常处理体系结构
    第2课.字符设备驱动程序的开发
    第1课.Linux驱动的概述
    [Linux驱动]字符设备驱动学习笔记(二)———实例
    [linux驱动]linux块设备学习笔记(三)——程序设计
    [Linux驱动]字符设备驱动学习笔记(一)
    [linux驱动]proc学习笔记(一)
    [linux驱动][Linux内存]DMA学习笔记一
  • 原文地址:https://www.cnblogs.com/bywallance/p/5637787.html
Copyright © 2011-2022 走看看