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

采用层序遍历的思路,用队列存储节点,然后一层一层去读,将每一层读取的结果插入result的头部。注意判断每层结束既可以用dummy节点,也可以在每层读取开始的时候判断队列当前的size,即可知道当前层的节点数量,这样比dummy的方式在代码上更为简洁。

/**
 * 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

递归函数中需要传入level参数,以便得知插入到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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容