【2错1对-1】Binary Tree Level Order Traversal II

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/

日期 是否一次通过 comment
2019-01-21 13:23 思路太僵
2019-01-22 00:00 Y 理解分层遍历
2019-05-14 00:00 Y 歇菜
【2错1对-1】Binary Tree Level Order Traversal II_第1张图片
image.png

(来源:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)

关键:Binary Tree Level Order Traversal ,层级遍历。只要把每层的结果插在最前面,因此LindedList这个结构非常适合

1. 非递归

class Solution {
    public List> levelOrderBottom(TreeNode root) {
        List> result = new LinkedList<>();
        
        if(root == null) {
            return result;
        }
        
        Queue nodeQ = new LinkedList<>();
        nodeQ.offer(root);
        
        while(!nodeQ.isEmpty()) {
            int qLen = nodeQ.size();
            List levelList = new ArrayList<>();
            for(int i=0; i

2.递归

class Solution {
    public List> levelOrderBottom(TreeNode root) {
        List> result = new LinkedList<>();
        
        if(root == null) {
            return result;
        }
        
        helper(root, result, 0);
        
        return result;
    }
    
    private void helper(TreeNode root, List> result, int level) {
        if(root == null) {
            return;
        }
        
        if(level >= result.size()) {
            result.add(0, new LinkedList<>());
        }
        
        result.get(result.size()-1 - level).add(root.val);
        if(root.left != null) {
            helper(root.left, result, level+1);
        }
        if(root.right != null) {
            helper(root.right, result, level+1);
        }
        
    }
    
}

你可能感兴趣的:(【2错1对-1】Binary Tree Level Order Traversal II)