首页 > 学院 > 开发设计 > 正文

105. Construct Binary Tree from Preorder and Inorder Traversal

2019-11-10 17:48:06
字体:
来源:转载
供稿:网友

Q

https://leetcode.com/PRoblems/construct-binary-tree-from-preorder-and-inorder-traversal/

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

A

/** * 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) { if (!preorderSize || !inorderSize || preorderSize != inorderSize) { return NULL; } struct TreeNode *p; p = (struct TreeNode *)malloc(sizeof(struct TreeNode)); p->val = *preorder; int i = 0; while(*preorder != inorder[i]) ++i; p->left = buildTree(preorder+1, i, inorder, i); p->right = buildTree(preorder+i+1, preorderSize-i-1, inorder+i+1, inorderSize-i-1); return p;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表