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

    Question

    Given preorder and inorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    Solution

    参考:http://www.cnblogs.com/zhonghuasong/p/7096150.html

    Code

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            if (preorder.size() == 0 || inorder.size() == 0)
                return NULL;
                
            return ConstructTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
        }
        
        TreeNode* ConstructTree(vector<int>& preorder, vector<int>& inorder, 
                int pre_start, int pre_end, int in_start, int in_end) {
            int rootValue = preorder[pre_start];
            TreeNode* root = new TreeNode(rootValue);
            if (pre_start == pre_end) {
                if (in_start == in_end)
                    return root;
            }
            
            int rootIn = in_start;
            while (rootIn <= in_end && inorder[rootIn] != rootValue)
                rootIn++;
                
            int preLeftLength = rootIn - in_start;
            if (preLeftLength > 0) {
                root->left = ConstructTree(preorder, inorder, pre_start + 1, preLeftLength, in_start, rootIn - 1);
            }
            // 左子树的对大长度就是in_end - in_start
            if (preLeftLength < in_end - in_start) {
                root->right = ConstructTree(preorder, inorder, pre_start + 1 + preLeftLength, pre_end, rootIn + 1, in_end);
            }
            
            return root;
        }
    };
    
  • 相关阅读:
    struts2上传下载
    git教程
    mysql触发器2
    mysql触发器
    mysql set sql_mode 1055 报错
    一些乱七八糟的话
    linux 命令2
    linux命令 mysql
    东南亚之行(越南篇)
    flume常见配置
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7096346.html
Copyright © 2011-2022 走看看