LeetCode - Flatten Binary Tree to Linked List
2016-01-13 13:44
465 查看
题目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
The flattened tree should look like:
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
思路:
递归,先flatten左边的,再flatten右边的,然后进行连接
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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
思路:
递归,先flatten左边的,再flatten右边的,然后进行连接
package tree; public class FlattenBinaryTreeToLinkedList { public void flatten(TreeNode root) { if (root == null) return; flatten(root.left); flatten(root.right); if (root.left != null) { TreeNode tmp = root.right; root.right = root.left; root.left = null; TreeNode rightMostNode = root; while (rightMostNode.right != null) { rightMostNode = rightMostNode.right; } rightMostNode.right = tmp; } } }
相关文章推荐
- C# 根据Word模版生成Word文件
- 学习 JavaScript 最难点之一 -- 理解prototype(原型)
- 快速排序
- Android退出应用最优雅的方式(改进版)
- C语言版本历史
- 深入分析JavaWeb Item51 -- Spring依赖注入
- Linux---密码重置与防范
- [Android] Android开发优化之——对Bitmap的内存优化
- php基础
- git分布式版本管理,配置流程,自己研究,win10
- Error:Execution failed for task ':app:clean'. > Unable to delete file: xxx.file
- 【杭电oj】5499 - SDOI(结构体排序,水)
- 第0条:拘泥于小节
- android 简单试题系统
- Hadoop科普文—常见的45个问题解答
- hdu 2055 An easy problem (java)
- 操作系统:基于页面置换算法的缓存原理详解(下)
- inline keyword in C
- 操作系统:基于页面置换算法的缓存原理详解(下)
- 值得学习的C语言开源项目