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

Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-01-30 22:50:28      阅读:266      评论:0      收藏: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.


#include<stdio.h>
#include<stdlib.h>

typedef struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
}TreeNode;

TreeNode *buildTreeCore(int *inorder, int inbegin, int inend, int *postorder, int postbegin, int postend) {
    TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
    root->val = postorder[postend];
    root->left = root->right = NULL;
    if(inbegin == inend || postbegin == postend) return root;
    int i;
    for(i = inend; i >= inbegin && postorder[postend] != inorder[i]; i--) ;
    if(i < inend) {
        root->right = buildTreeCore(inorder, i + 1, inend, postorder, postbegin + i - inbegin, postend - 1);
    }
    if(i > inbegin) {
        root->left = buildTreeCore(inorder, inbegin, i - 1, postorder, postbegin, postbegin + i - inbegin - 1);
    }
    return root;
}

TreeNode *buildTree(int *inorder, int *postorder, int n) {
    if(inorder == NULL || postorder == NULL) return NULL;
    TreeNode *root = buildTreeCore(inorder, 0, n - 1, postorder, 0, n - 1);
}

void Travel(TreeNode *root) {
    if(root != NULL) {
        printf("%d, ", root->val);
        Travel(root->left);
        Travel(root->right);
    }
}

void main() {
    int in[] = {1, 2, 3, 4, 5, 6};
    int post[] = {1, 2, 4, 5, 6, 3};
    TreeNode *root = buildTree(in, post, 6);
    Travel(root);
    printf("\n");
}


Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://blog.csdn.net/uj_mosquito/article/details/43309807

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