107. 二叉樹的層次遍歷 II
給定一個二叉樹,返回其節點值自底向上的層次遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)
例如:
給定二叉樹 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的層次遍歷爲:
[
[15,7],
[9,20],
[3]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
-
創建二叉搜索樹
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
-
1. 迭代法
思路:
- 創建一個隊列,將根節點添加進隊列中
- 遍歷該隊列,獲取隊列的大小,取出隊首的元素,將其加入到 temp 中,依次將其左右節點加入隊列中,
- 將 temp 加入 list 中即可.
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if (root == null) return list;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> temp = new ArrayList<>();
while (size > 0) {
TreeNode cur = queue.poll();
temp.add(cur.val);
if (cur.left != null) queue.add(cur.left);
if (cur.right != null) queue.add(cur.right);
size--;
}
list.add(temp);
}
//反轉list
Collections.reverse(list);
return list;
}
複雜度分析:
時間複雜度:O(n), 需要遍歷每個元素添加到隊列中
空間複雜度:O(n), 複雜度爲隊列的空間大小,也就是節點數量
-
2. 遞歸法
- 遞歸終止條件爲當前節點爲空
- 如果當前處於第新的一層時,就爲 list 中第0個元素創建新的 list, 用於存儲節點值
- 將節點的值添加進去
- 依次添加左右子樹節點
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
return list;
}
private void helper(TreeNode root, List<List<Integer>> list, int depth) {
if (root == null) return;
//將元素添加到index位置,如果原位置已經有元素了,就將原來的元素向右移動
if (list.size() == depth) list.add(0, new ArrayList<>());
list.get(list.size() - depth - 1).add(root.val);
helper(root.left, list, depth + 1);
helper(root.right, list, depth + 1);
}
複雜度分析:
- 時間複雜度:O(n), 需要遍歷每個元素添加到隊列中
- 空間複雜度:O(n), 使用了遞歸
-
源碼
-
我會每天更新新的算法,並儘可能嘗試不同解法,如果發現問題請指正
- Github