題目要求:給定一棵二叉樹,原地將其展開為單鏈表,展開後的順序為前序遍歷順序。
輸入:
1
/ \
2 5
/ \ \
3 4 6
輸出:
1
\
2
\
3
\
4
\
5
\
6
List。left 設為 null,right 指向下一個節點。/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
if (root == null) return;
List list = preOrder(root);
TreeNode p = root;
for (int i = 1; i < list.size(); i++) {
p.right = list.get(i);
p.left = null;
p = p.right;
}
}
public List preOrder(TreeNode root) {
List list = new ArrayList<>();
if (root == null) return list;
list.add(root);
if (root.left != null) list.addAll(preOrder(root.left));
if (root.right != null) list.addAll(preOrder(root.right));
return list;
}
}
進階:可嘗試 Morris 遍歷將空間優化至 O(1)。