Flatten Binary Tree to Linked List
2015-06-09 09:29
197 查看
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.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
/**
* 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 == NULL) return;
TreeNode* temp = root->left;//左子树
if(temp != NULL){
while(temp->right != NULL){//左子树的最右节点
temp = temp->right;
}
temp->right = root->right;//右子树接到左子树的最右节点的右孩子
root->right = root->left;//转移左子树到右子树
root->left = NULL;//左子树置空
}
flatten(root->right);//递归处理右接孩子
}
};
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.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
/**
* 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 == NULL) return;
TreeNode* temp = root->left;//左子树
if(temp != NULL){
while(temp->right != NULL){//左子树的最右节点
temp = temp->right;
}
temp->right = root->right;//右子树接到左子树的最右节点的右孩子
root->right = root->left;//转移左子树到右子树
root->left = NULL;//左子树置空
}
flatten(root->right);//递归处理右接孩子
}
};
相关文章推荐
- Android中使用二级缓存、异步加载批量加载图片完整案例
- android 获取 imei号码
- 解决Win7下运行php Composer出现SSL报错的问题
- 用ListView+自定义的HorizontalScrollView实现滑动删除效果
- Android中LayoutInflater的使用
- 那些年踩过的坑之:first-child伪类选择器
- visual studio 辅助工具
- MyBatis学习门户网站(一)
- Google Develop for Android 连接地址
- oracle中表示本周的周日和下周的周日
- 深入理解Java:注解(Annotation)基本概念
- 关于slave的replicate-ignore-db 参数 跨库问题
- 题目1005:Graduate Admission
- SSH级联操作报错:org.hibernate.exception.ConstraintViolationException: Could not execute
- 使用grunt来无损压缩图片
- clog、blob、bfile、long
- 利用a标签特性解析地址(附加属性说明)
- Android LinearLayout中TextView标签项自动换行的一种解决方案(二)
- 详解Python正则表达式之: (?P<name>…) named group 带命名的组
- 隐马尔科夫学习五(二)