114. Flatten Binary Tree to Linked List
来源:互联网 发布:nosql和mysql结合 编辑:程序博客网 时间:2024/04/30 07:43
114 . Flatten Binary Tree to Linked List
Difficulty: Medium
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
解题思路
仔细看看这道题会很快发现,我们其实只要先序遍历整棵树,并且在遍历过程当中将重排问题同步解决就可以了。
在实现过程中,最为麻烦的是将函数尽可能优化,因为要一边搜索一边重排,这就意味着如果没有合理的结构就会有不好的结果。
我在这里使用的就是循环思路,将左子树不断插入到右子树中去即可。中间就是不断遍历左边的树并且一步步让root指向root-〉right即可。
具体实现
/** * 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; while(root) { if(root->left) { TreeNode *pre = root->left; while(pre->right) pre = pre->right; pre->right = root->right; root->right = root->left; root->left = NULL; } root = root->right; } }};
0 0
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 114. Flatten Binary Tree to Linked List
- 多视角学习-协同训练
- hdu5245 Joyful(概率dp)
- KDD(数据挖掘)概念
- DateTime TryParse方法,介绍
- PySpark-aggregate函数说明
- 114. Flatten Binary Tree to Linked List
- docker学习11--私有仓库registry设置
- 非对称加密算法之RSA
- Linux IO : 阻塞、非阻塞、同步、异步
- Python 爬虫的工具列表( 附Github代码下载链接)
- Openfire 源码部署
- 如何写一个通用的列表控件
- 使用PHP生成PDF文档
- BZOj2790/POI2012 Distance