[Leetcode 114, Medium] Flatten Binary Tree to Linked List
2015-07-26 10:37
591 查看
Problem:
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.
Analysis:
Solutions:
C++:
Python:
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
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.
Analysis:
Solutions:
C++:
void flatten(TreeNode* root) { if(root == NULL) return; if(root->left) flatten(root->left); if(root->right) flatten(root->right); if(root->left) { TreeNode *temp_left = root->left; root->left = NULL; TreeNode *temp_right = root->right; root->right = temp_left; TreeNode *p_cur = root->right; for(; p_cur->right != NULL; p_cur = p_cur->right) {} p_cur->right = temp_right; } }Java:
Python:
相关文章推荐
- 两种方法交换变量的值
- HDU 1215 七夕节 因子求和
- 利用Metasploit测试一个古老的IE8漏洞(编号CVE-2012-1875)
- git 首次将本地文件上传到服务器和git常用命令
- 微信上抽奖的界面
- 算法入门
- Spring Mvc——初始化
- 【Thinking in Java笔记】为什么需要内部类
- uva11426(gcd + 欧拉函数)
- ubuntu下mysql的常用命令
- 机器学习(5)——过拟合问题
- 【试水CAS-4.0.3】第06节_CAS服务端配置HTTPS
- ajax post方法
- javascript获取当前的时间戳的方法汇总
- Android四大组件及意图和意图过滤器
- C语言中数组越界的例子
- View 和 ViewGroup 的 hasFocusable
- BigDecimal 类运算
- vim 配置
- 利用git bash的工作流程