LeetCode题库解答与分析——#107. 二叉树的层次遍历 IIBinaryTreeLevelOrderTraversal

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其自自底向上的层次遍历为:

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

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],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

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

个人思路:

参考二叉树的层次遍历的思路,但总的结果用栈存储,最后再一次弹出,从而使各个分数组逆序排列

代码(JavaScript):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List> levelOrderBottom(TreeNode root) {
        Queue queue=new LinkedList();
        Stack> visited=new Stack>();
        List> result=new LinkedList>();
        int row=0,col=0;
        if(root!=null){queue.offer(root);}
        else{return visited;}
        while(!queue.isEmpty()){
            int level=queue.size();
            List sub_visited=new LinkedList();
            for(int i=0;i


你可能感兴趣的:(LeetCode,LeetCode,算法,树,广度优先搜索)