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

    来源:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal

    Java

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11     public TreeNode buildTree(int[] preorder, int[] inorder) {
    12         if(preorder.length == 0) {
    13             return null;
    14         }
    15         TreeNode root = new TreeNode(preorder[0]);
    16         int rootIndex = 0;
    17         while(rootIndex < inorder.length) {
    18             if(inorder[rootIndex] == preorder[0]) {
    19                 break;
    20             }
    21             rootIndex++;
    22         }
    23         int[] preLeftSubTree = Arrays.copyOfRange(preorder, 1, rootIndex+1);
    24         int[] preRightSubTree = Arrays.copyOfRange(preorder, rootIndex+1, preorder.length);
    25         int[] inLeftSubTree = Arrays.copyOfRange(inorder, 0, rootIndex);
    26         int[] inRightSubTree = Arrays.copyOfRange(inorder, rootIndex+1, inorder.length);
    27         root.left = buildTree(preLeftSubTree, inLeftSubTree);
    28         root.right = buildTree(preRightSubTree, inRightSubTree);
    29         return root;
    30     }
    31 }// 36 ms,待优化,去掉数组拷贝

    Python

     1 # -*- coding:utf-8 -*-
     2 # class TreeNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 class Solution:
     8     # 返回构造的TreeNode根节点
     9     def reConstructBinaryTree(self, pre, tin):
    10         if len(pre) == 0:
    11             return None
    12         if len(pre) == 1:
    13             return TreeNode(pre[0])
    14         head = TreeNode(pre[0])
    15         head.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1], tin[:tin.index(pre[0])])
    16         head.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:], tin[tin.index(pre[0])+1:])
    17         return head
  • 相关阅读:
    MFC线程(二):线程同步临界区CRITICAL SECTION
    自定义消息
    Visual C++线程同步技术剖析:临界区,时间,信号量,互斥量
    //解析数据函数指针,很爽
    CListCtrl使用方法汇总
    进度条的使用 Progress控件
    CListBOX 用法
    文件操作总结
    CString 十六进制转二进制
    Numpy常用数据结构、数据清洗函数、数据结构series和方法、数据结构dataframe和方法
  • 原文地址:https://www.cnblogs.com/renzongxian/p/7535925.html
Copyright © 2011-2022 走看看