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<List<Integer>> levelOrderBottom(TreeNode root) {
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        Stack<List<Integer>> visited=new Stack<List<Integer>>();
        List<List<Integer>> result=new LinkedList<List<Integer>>();
        int row=0,col=0;
        if(root!=null){queue.offer(root);}
        else{return visited;}
        while(!queue.isEmpty()){
            int level=queue.size();
            List<Integer> sub_visited=new LinkedList<Integer>();
            for(int i=0;i<level;i++){
                if(queue.peek().left!=null){queue.offer(queue.peek().left);}
                if(queue.peek().right!=null){queue.offer(queue.peek().right);}
                sub_visited.add(queue.poll().val);
            }
            visited.push(sub_visited);
        }
        while(!visited.isEmpty()){
            result.add(visited.pop());
        }
        return result;
    }
}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页