114. Flatten Binary Tree to Linked List
2016-07-26 11:00
393 查看
**
题目
–
**
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
**
题意: 将二叉树转为左子树为空的二叉树,很明显,转化后的二叉树为原二叉树的先序遍历序列;
**
-
题目
–
**
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
**
- 求解过程
**题意: 将二叉树转为左子树为空的二叉树,很明显,转化后的二叉树为原二叉树的先序遍历序列;
**
-
代码:
**class Solution { public: void flatten(TreeNode* root) { if(root == NULL || (root->left==NULL && root->right == NULL)) { return ; } flatten(root->left); //先转换左子树 flatten(root->right);//再转换右子树 TreeNode* tmpright = root->right; //临时保存右子树 root->right = root->left; //再将转换后左子树赋给右子树 root->left = NULL; //再把左子树赋值为空树 TreeNode* tr = root; while(tr->right) //找到转换后的右子树(原左子树)的最后一个节点 { tr = tr->right; } tr->right = tmpright; //最后将原右子树拼接到找到的最后的节点之后 } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解