码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal

时间:2016-11-22 02:58:48      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:scribe   and   cat   node   font   style   turn   break   dtree   

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

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

 

Subscribe to see which companies asked this question

解答

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
    struct TreeNode *node;
    int i;
    
    if(0 >= preorderSize||0 >= inorderSize){
        return NULL;
    }
    node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    node->val = preorder[0];
    for(i = 0; i < inorderSize; i++){
        if(inorder[i] == preorder[0]){
            break;
        }
    }
    node->left = buildTree(preorder + 1, i, inorder, i);
    node->right = buildTree(preorder + i + 1, preorderSize - 1 - i, inorder + i + 1, preorderSize - 1 - i);
    return node;
}

 

LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal

标签:scribe   and   cat   node   font   style   turn   break   dtree   

原文地址:http://www.cnblogs.com/YuNanlong/p/6087540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!