给定一棵树的前序遍历与中序遍历,依据此构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 = [3,9,20,15,7]
中序遍历 = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
详见:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int is=inorder.size(); if(is==0||inorder.empty()) { return nullptr; } int val=preorder[0]; TreeNode* root=new TreeNode(val); vector<int> pre_left,pre_right,in_left,in_right; int p=0; for(;p<is;++p) { if(inorder[p]==val) { break; } } for(int i=0;i<is;++i) { if(i<p) { pre_left.push_back(preorder[i+1]); in_left.push_back(inorder[i]); } else if(i>p) { pre_right.push_back(preorder[i]); in_right.push_back(inorder[i]); } } root->left=buildTree(pre_left,in_left); root->right=buildTree(pre_right,in_right); return root; } };
原文地址:https://www.cnblogs.com/xidian2014/p/8719081.html
时间: 2024-10-08 12:10:55