[Leetcode]Flatten Binary Tree to Linked List
2015-10-11 17:04
351 查看
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
The flattened tree should look like:
click to show hints.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
click to show hints.
/** * 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: void preorder(TreeNode* root,TreeNode* &tail){ if(!root)return; TreeNode* l = root->left,*r = root->right; if(tail)tail->right = root; tail = root; tail->left = NULL; preorder(l,tail); preorder(r,tail); } void flatten(TreeNode* root) { //preorder TreeNode* tail = NULL; preorder(root,tail); } };
class Solution { public: void flatten(TreeNode* root) { stack<TreeNode*>stk; if(root)stk.push(root); TreeNode* tail = NULL; while(!stk.empty()){ TreeNode* t = stk.top();stk.pop(); if(t->right)stk.push(t->right); if(t->left)stk.push(t->left); if(tail)tail->right = t; tail = t; tail->left = NULL; } } };
相关文章推荐
- 数据挖掘导论笔记之探索数据
- sicily 1050. Numbers & Letters
- 145.Binary Tree Postorder Traversal
- Maven打包jar项目
- rhel7 设置计划任务cron
- 关于python测试webservice接口的视频分享
- 关于python测试webservice接口的视频分享
- Matlab中绘制网格图和等高线:mesh 和 surf
- sicily 1009. Mersenne Composite N
- 反应器(Reactor)模式
- iOS 开发笔记-控制器tab切换view显示
- 20135210程涵——信息安全系统设计基础第五周学习总结
- 关于懒加载的一些小细节
- this;static 介绍
- Bellman-Ford-POJ-1860-Currency Exchange
- vim查找替换,转载自实验楼
- foreach语句使用总结
- sicily 1007. To and Fro
- sg函数学习小结
- 使用 Spring Data JPA 简化 JPA 开发