LeetCode 107. Binary Tree Level Order Traversal II

Posted sevenun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 107. Binary Tree Level Order Traversal II相关的知识,希望对你有一定的参考价值。

题意:给你个二叉树,要求按深度下到上,输出每行的整数。

 

我的思路:我采用了广度优先搜索,并利用两个变量,来计算当前所遍历的深度,然后就把每个深度的整数都加入到容器里,一旦深度+1 就把该容器添加到总容器里。

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        return bfs(root);
    }
    
    private List<List<Integer> > bfs(TreeNode root) {
        List<List<Integer> > ans = new ArrayList<>();
        if (root == null) return ans;
        
        Queue<TreeNode> Q = new LinkedList<TreeNode>();
        Q.add(root);
        
        TreeNode endRight = root;     //记录当前深度最右边的节点
        TreeNode currentRight = null; //记录当前遍历的节点中最右边的孩子节点
        
        List<Integer> list = new ArrayList<>();
        
        while (!Q.isEmpty()) {
            TreeNode t = Q.poll();
            list.add(t.val);
            
            if(t.left != null) {
                Q.add(t.left);
                currentRight = t.left;
            }
            if(t.right != null) {
                Q.add(t.right);
                currentRight = t.right;
            }
            if(t == endRight) {   //如果当前节点等于当前深度最右边的节点,那么深度就要+1了
                endRight = currentRight;
                ans.add(0, list);
                list = new ArrayList<>();
            }
        }
        return ans;
    }
}

  

以上是关于LeetCode 107. Binary Tree Level Order Traversal II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode107. Binary Tree Level Order Traversal II 解题报告

LeetCode_107. Binary Tree Level Order Traversal II

Leetcode 107 Binary Tree Level Order Traversal II

LeetCode107 Binary Tree Level Order Traversal II

Leetcode 107. Binary Tree Level Order Traversal II

LeetCode 107.Binary Tree Level Order Traversal II