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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 105. 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.

 

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的主要内容,如果未能解决你的问题,请参考以下文章

oj--cs10116 final exam

Light oj 1422 - Halloween Costumes

南阳oj 蛇形填数

oj---九度oj---1061

oj---九度oj---1434

oj---九度oj---1009