题解 | #输出二叉树的右视图#
输出二叉树的右视图
http://www.nowcoder.com/practice/c9480213597e45f4807880c763ddd5f0
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(pre.empty()||vin.empty())return NULL;
TreeNode* root = new TreeNode(pre[0]);
stack<TreeNode* > tmp;
tmp.push(root);
int t=0;
for(int i=1;i<pre.size();i++){
TreeNode* node = tmp.top();
if(node->val!=vin[t]){
node->left = new TreeNode(pre[i]);
tmp.push(node->left);
}
else{
while(!tmp.empty()&&tmp.top()->val==vin[t]){
node = tmp.top();
tmp.pop();
t++;
}
node->right = new TreeNode(pre[i]);
tmp.push(node->right);
// node->right = new TreeNode(pre[i]);
// t++;
// tmp.pop();
// tmp.push(node->right);
}
}
return root;
}
};