LeetCode114 Flatten Binary Tree to Linked List
2016-11-16 22:28
363 查看
Given a binary tree, flatten it to a linked list in-place. (Medium)
For example,
Given
The flattened tree should look like:
分析:
将树的问题和链表插入问题结合。对于每个节点,寻找左子树的最右端,它应该是左子树前序遍历的最后一位,也就是生成链表中,右子树根节点的前一位。
按照链表插入的方法处理即可。
代码:
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
分析:
将树的问题和链表插入问题结合。对于每个节点,寻找左子树的最右端,它应该是左子树前序遍历的最后一位,也就是生成链表中,右子树根节点的前一位。
按照链表插入的方法处理即可。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void flatten(TreeNode* root) { 13 if (root == nullptr) { 14 return; 15 } 16 while (root != nullptr) { 17 if (root -> left != nullptr) { 18 TreeNode* temp = root -> left; 19 while (temp -> right != nullptr) { 20 temp = temp -> right; 21 } 22 temp -> right = root -> right; 23 root -> right = root -> left; 24 root -> left = nullptr; 25 } 26 root = root -> right; 27 } 28 } 29 };
相关文章推荐
- LeetCode-114:Flatten Binary Tree to Linked List
- [Leetcode 114, Medium] Flatten Binary Tree to Linked List
- leetcode 114 . Flatten Binary Tree to Linked List
- LeetCode 114 Flatten Binary Tree to Linked List
- 【LeetCode 114】Flatten Binary Tree to Linked List (C++)
- Java for LeetCode 114 Flatten Binary Tree to Linked List
- LeetCode 114 Flatten Binary Tree to Linked List
- [LeetCode]114 Flatten Binary Tree to Linked List
- LeetCode(114) Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List - LeetCode 114
- LeetCode114—Flatten Binary Tree to Linked List
- LeetCode(114) Flatten Binary Tree to Linked List
- leetcode——114—— Flatten Binary Tree to Linked List
- [Leetcode 81] 114 Flatten Binary Tree to Linked List
- 【LeetCode-面试算法经典-Java实现】【114-Flatten Binary Tree to Linked List(二叉树转单链表)】
- leetcode114~Flatten Binary Tree to Linked List
- 【LeetCode从零单排】No 114 Flatten Binary Tree to Linked List
- LeetCode(114) Flatten Binary Tree to Linked List
- leetcode_question_114 Flatten Binary Tree to Linked List
- LeetCode 114 Flatten Binary Tree to Linked List