107. Binary Tree Level Order Traversal II

Description

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

return its bottom-up level order traversal as:

Solution

BFS

采用層序遍歷的思路,用隊(duì)列存儲(chǔ)節(jié)點(diǎn),然后一層一層去讀,將每一層讀取的結(jié)果插入result的頭部。注意判斷每層結(jié)束既可以用dummy節(jié)點(diǎn),也可以在每層讀取開始的時(shí)候判斷隊(duì)列當(dāng)前的size,即可知道當(dāng)前層的節(jié)點(diǎn)數(shù)量,這樣比dummy的方式在代碼上更為簡(jiǎn)潔。

/**
 * 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) {
        List<List<Integer>> levels = new LinkedList();
        if (root == null) return levels;
        
        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);
        
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList();
            int nodesNum = queue.size();    // a snapshot representing nodes count of current level
            
            for (int i = 0; i < nodesNum; ++i) {
                TreeNode p = queue.poll();
                if (p.left != null) queue.add(p.left);
                if (p.right != null) queue.add(p.right);
                level.add(p.val);
            }
            levels.add(0, level);
        }
        
        return levels;
    }
}

DFS

遞歸函數(shù)中需要傳入level參數(shù),以便得知插入到result的位置。

/**
 * 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) {
        List<List<Integer>> levelsList = new LinkedList();
        levelMaker(levelsList, root, 0);
        return levelsList;
    }
    
    public void levelMaker(List<List<Integer>> levelsList, TreeNode root, int level) {
        if (root == null) return;
        if (level >= levelsList.size()) levelsList.add(0, new ArrayList());
        levelMaker(levelsList, root.left, level + 1);
        levelMaker(levelsList, root.right, level + 1);
        levelsList.get(levelsList.size() - level - 1).add(root.val);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容