Flatten Binary Tree to Linked List - LeetCode 114
2015-06-15 20:29
411 查看
题目描述:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
分析:
根据先序优先序列的顺序,全部添加到右子树,左子树全部为空。采用深度优先遍历即可。
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
分析:
根据先序优先序列的顺序,全部添加到右子树,左子树全部为空。采用深度优先遍历即可。
/**///////////////8ms/////*/ /** * 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 flatten(TreeNode* root) { if(!root) return; TreeNode *cur = root; stack<TreeNode* > s; TreeNode *head = new TreeNode(root->val); //添加根节点 TreeNode *tmp = head; if(root->right != NULL) s.push(root->right); if(root->left != NULL) s.push(root->left); while(!s.empty()){ cur = s.top(); s.pop(); tmp->left = NULL; tmp->right = new TreeNode(cur->val); tmp = tmp->right; if(cur->right != NULL) s.push(cur->right); if(cur->left != NULL) s.push(cur->left); } root ->right = head->right; //将根节点右子树更新为新根节点的右子树,左子树为空 root->left = NULL; return; } };
相关文章推荐
- 【Scala】特质与特质的线性化
- OC中文件读取类(NSFileHandle)介绍和常用使用方法
- Android多点触控技术
- 关于ffmpeg的avpacket里的pts问题
- Adboost
- proftpd的mod_copy模块未授权调用利用记录
- 【Scala】Scala的类层级
- Javascript 类的实现
- bzoj 1095 括号序列求两点距离
- Platform设备驱动
- JS显示动态显示当前时间代码
- 黑马程序员——Java基础之函数与数组
- Picture控件显示jpg
- 十、迭代器和组合模式
- 【Scala】高阶函数和柯里化
- 新手学习编程的最佳方式是什么?
- Android: 一个两点触控的案例
- 《编程珠玑》阅读小记(9) — 取样问题
- oracle中rowid解决数据重复的问题
- WebX学习二——URL请求流程分析