首页 > 代码库 > LeetCode OJ 105. Construct Binary Tree from Preorder and Inorder Traversal
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。