美文网首页
Leetcode 106. Construct Binary T

Leetcode 106. Construct Binary T

作者: persistent100 | 来源:发表于2017-12-11 16:34 被阅读0次

题目

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

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

分析

根据树的中序和后续,构造出该二叉树。先找出根节点,然后分析左右子树。

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

相关文章

网友评论

      本文标题:Leetcode 106. Construct Binary T

      本文链接:https://www.haomeiwen.com/subject/bllabxtx.html