leetcode算法練習【107】二叉樹的層次遍歷 II

所有題目源代碼:Git地址

題目

給定一個二叉樹,返回其節點值自底向上的層次遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)

例如:
給定二叉樹 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其自底向上的層次遍歷爲:

[
  [15,7],
  [9,20],
  [3]
]

方案:

  • 思路同102,數組倒過來存即可
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
            // 層序
            int size = 1;
            TreeNode tmp;
            //利用隊列來實現層序遍歷
            LinkedList<TreeNode> list = new LinkedList<>(); 
            List<List<Integer>> res = new LinkedList<>();
            if(root==null) return res;
            list.add(root);
            while(list.size()>0){
                //開始遍歷
                List<Integer> nums = new LinkedList<>();
                size = list.size();
                for(int i =0;i<size;i++){
                    tmp = list.removeFirst();
                    //如果還有下一層,那就入隊
                    if(tmp.left!=null) {list.add(tmp.left);}
                    if(tmp.right!=null) {list.add(tmp.right);}
                    nums.add(tmp.val);
                }
                res.add(0,nums);
            }
            return res;
    }
}
複雜度計算
  • 時間複雜度:O(n)
  • 空間複雜度:O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章