【一天一道LeetCode】#114. Flatten Binary Tree to Linked List
来源:互联网 发布:java框架cs通讯 编辑:程序博客网 时间:2024/06/07 05:08
一天一道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(一)题目
Given a binary tree, flatten it to a linked list in-place.
For example,
Given1 / \ 2 5 / \ \3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
(二)解题
题目大意:将一个二叉树转换成平树(google来的翻译)
看图就大概知道题目的意思了。
解题思路:flattened tree的顺序就是原树的前序遍历。所以可以定义一颗新树,按照前序遍历来生成右子树。
具体见代码:
/** * 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: TreeNode* newroot = NULL;//新树的根节点 TreeNode* p = newroot;//循环中间变量 void flatten(TreeNode* root) { if(root==NULL) return; preorder(root);//前序遍历 //这里有个疑惑:为什么roor=newroot不行? root->right = newroot->right; root->left = NULL; } void preorder(TreeNode* root)//中序遍历 { TreeNode* temp = new TreeNode(root->val); if(newroot==NULL) newroot=temp;//保存根节点 else p->right=temp;//构造右子树 p = temp; if(root->left!=NULL) preorder(root->left); if(root->right!=NULL) preorder(root->right); }};
0 0
- 【一天一道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
- 15 个 Android 通用流行框架大全
- LeetCode - 65. Valid Number
- 【JavaWeb开发】Windows系统中JDK环境的配置
- AndroidStudio多渠道打包
- unity 网格切割
- 【一天一道LeetCode】#114. Flatten Binary Tree to Linked List
- 用J-Link给开发板供电
- 跟我一起学Multiple View Geometry多视图几何(2)
- 调试 了解骨骼坐标变化
- elasticsearch从mysql导入数据
- 解决STM32在MDK-ARM(KEIL)编译时出现 已停止工作
- 许式伟《Go语言编程》样章“面向对象编程”
- Python学习笔记1:Python是什么?
- private、protected、public权限修饰符详解