Flatten Binary Tree to Linked List问题及解法
来源:互联网 发布:淘宝显示历史价格 编辑:程序博客网 时间:2024/05/16 04:17
问题描述:
Given a binary tree, flatten it to a linked list in-place.
示例:
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6问题分析:
由题意可知,我们可以先把树的结点按照先序遍历存到数组vec中,然后遍历数组,修改指针,首尾相接即可。
过程详见代码:
/** * 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 preorder(TreeNode* root, vector<TreeNode*>& vec){ if(root == NULL) return; vec.push_back(root); preorder(root->left, vec); preorder(root->right, vec); } void flatten(TreeNode* root) { vector<TreeNode*> vec; preorder(root, vec); for(int i = 0; i < (int)vec.size()-1; ++i){ vec[i]->right = vec[i+1]; vec[i]->left = NULL; } }};
阅读全文
0 0
- Flatten Binary Tree to Linked List问题及解法
- LeetCode: Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- [Leetcode] Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- Leetcode: Flatten Binary Tree to Linked List
- leetcode Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- 【leetcode】Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- [LeetCode]Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- HPUoj 1409: Watch Dog [最小生成树]
- [ZOJ1654]放置机器人
- HPU 1410: QAQ & 火星情报局 ( 数学
- 1412: QAQ & 君临天下 || 天行九歌 [区间]
- HPUoj 1413: StarFarming [最短路]
- Flatten Binary Tree to Linked List问题及解法
- List更新20171024
- Ruijie—Telnet控制交换机
- HPUoj 1415: 小ho的01串 [字符串]
- ffmpeg + nginx + rtmp 搭建本地直播服务器
- 利比亚行动
- Populating Next Right Pointers in Each Node问题及解法
- SSL P2574 Closest
- 【usaco】learning