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

    没什么好说的,了解原理即可,使用递归。

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder, int a, int b, int n) {
    13         TreeNode *root = NULL;
    14         if (n < 1) {
    15             return root;
    16         }
    17         root = new TreeNode(preorder[a]);
    18         bool flag = false;
    19         int i;
    20         for (i = 0; i < n; ++i) {
    21             if (inorder[b+i] == preorder[a]) {
    22                 break;
    23             }
    24         }
    25         root->left = buildTree(preorder, inorder, a+1, b, i);
    26         root->right = buildTree(preorder, inorder, a+i+1, b+i+1, n-1-i);
    27         return root;
    28     }
    29 
    30     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
    31         int n = preorder.size();
    32         return buildTree(preorder, inorder, 0, 0, n);
    33         
    34     }
    35 };
  • 相关阅读:
    redis命令
    eclipse error pages 打红X的解决方法
    探究adroid活动
    Javascript基本算法演练 Seek and Destroy
    c语言结构体排序示例
    android studio 环境配置
    git学习
    栈用于2进制转换10进制
    html和js
    js
  • 原文地址:https://www.cnblogs.com/easonliu/p/3630644.html
Copyright © 2011-2022 走看看