【C++】【LeetCode】114. Flatten Binary Tree to Linked List
来源:互联网 发布:网络工具书 编辑:程序博客网 时间:2024/06/05 23:47
题目
Given a binary tree, flatten it to a linked list in-place.
思路
有两种方法,第一种比较笨,把所有的点按照前序遍历存入队列,然后取出来构建一棵树;还有一种,把左子树的最右叶子节点找到,将右子树作为最右叶子节点的右子树,然后将左子树作为右子树。
代码
思路一/** * 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 ; } std::queue<TreeNode*> s; helper(s, root); TreeNode *head = root; s.pop(); while (s.size() > 0) { head->right = s.front(); head->left = NULL; head = head->right; s.pop(); } } void helper(std::queue<TreeNode*>& s, TreeNode* root) { if (root == NULL) { return; } s.push(root); helper(s, root->left); helper(s, root->right); }};
思路二class Solution {public: void flatten(TreeNode *root) { TreeNode*now = root; while (now) { if(now->left) { //Find current node's prenode that links to current node's right subtree TreeNode* pre = now->left; while(pre->right) { pre = pre->right; } pre->right = now->right; //Use current node's left subtree to replace its right subtree(original right //subtree is already linked by current node's prenode now->right = now->left; now->left = NULL; } now = now->right; } }};
阅读全文
0 0
- 【C++】【LeetCode】114. 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
- [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
- 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
- [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
- LeetCode:Flatten Binary Tree to Linked List
- vs2017使用libfdk-aac 链接提示没有“COMDAT 0xF”错误解决
- 自定义Toast
- 【基础算法】 书的复制
- 数位DP专题总结
- PHP 正则表达式常用函数使用小结
- 【C++】【LeetCode】114. Flatten Binary Tree to Linked List
- 地址映射
- 构建乘积数组
- GitHub 实现多人协同提交代码并且权限分组管理
- 数据结构解析
- 华为平板输出日志
- TensorFlow on Android
- 鸿洋博客精选
- FastDFS 5.05的安装成功案例 ---整合nginx-1.8.0,Http 访问 Linux环境