114-Flatten Binary Tree to Linked List
Description
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
問題描述
給定二叉樹, 原位將它壓縮為連結串列
問題分析
後序遍歷, 先處理右子樹後處理左子樹, 注意將左子樹設定為null
解法
class Solution {
public void flatten(TreeNode root){
flatten(root, null);
}
private TreeNode flatten(TreeNode root, TreeNode pre) {
if(root == null) return pre;
//注意這裡pre的變化
pre = flatten(root.right, pre);
pre = flatten(root.left, pre);
root.right = pre;
//注意這裡
root.left = null;
pre = root;
return pre;
}
}
相關文章
- [LeetCode] 1367. Linked List in Binary Tree 二叉樹中的連結串列LeetCode二叉樹
- [LeetCode] 109. Convert Sorted List to Binary Search TreeLeetCode
- Java for LeetCode 109 Convert Sorted List to Binary Search TreeJavaLeetCode
- Traversals of binary tree
- Leetcode Binary Tree PathsLeetCode
- LeetCode | 141 linked list cycleLeetCode
- [LintCode] Check Full Binary Tree
- 257-Binary Tree Paths
- 543-Diameter of Binary Tree
- 563-Binary Tree Tilt
- 655-Print Binary Tree
- 654-Maximum Binary Tree
- 814-Binary Tree Pruning
- 110-Balanced Binary Tree
- 545. Boundary of Binary Tree
- 257. Binary Tree Paths
- Construct String from Binary TreeStruct
- 226-Invert Binary Tree
- [LintCode] Binary Tree Level Order
- 328. Odd Even Linked List
- [leetcode]linked-list-cycle-iiLeetCode
- Leetcode 206. Reverse Linked ListLeetCode
- 92. Reverse Linked List II
- Leetcode 234. Palindrome Linked ListLeetCode
- LeetCode 382 Linked List Random NodeLeetCoderandom
- [LeetCode] 226. Invert Binary TreeLeetCode
- [LeetCode] 543. Diameter of Binary TreeLeetCode
- 111-Minimum Depth of Binary Tree
- 662-Maximum Width of Binary Tree
- Binary-tree-level-order-traversal
- 104. Maximum Depth of Binary Tree
- LeetCode 543. Diameter of Binary TreeLeetCode
- Binary Tree Level Order Traversal [LEETCODE]LeetCode
- LeetCode545.Boundary-of-Binary-TreeLeetCode
- Leetcode 226. Invert Binary TreeLeetCode
- [leetcode]binary-tree-inorder-traversalLeetCode
- [leetcode]maximum-depth-of-binary-treeLeetCode
- LeetCode之Univalued Binary Tree(Kotlin)LeetCodeKotlin