LeetCode 107 Binary Tree Level Order Traversal II

来源:互联网 发布:ubuntu中的火狐浏览器 编辑:程序博客网 时间:2024/06/04 00:54
题目


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,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its bottom-up level order traversal as:

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

反向层遍历



思路


  和之前的广度遍历一样,只不过,考察arraylist的反转会不会


代码


 

public class Solution {    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {        ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();        ArrayList<Integer> temp = new ArrayList<Integer>();        if(root==null){            return ans;        }        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();        queue.add(root);        int num =0;        int count =1;        while(!queue.isEmpty()){            TreeNode cur = queue.remove();            temp.add(cur.val);            count--;            if(cur.left!=null){                queue.add(cur.left);                num++;            }            if(cur.right!=null){                queue.add(cur.right);                num++;            }            if(count==0){                ans.add(new ArrayList<Integer>(temp));                temp.clear();                count = num;                num =0;            }        }        ArrayList<ArrayList<Integer>> ans2 = new ArrayList<ArrayList<Integer>>();        for(int i =ans.size()-1;i>=0;i--){            ans2.add(ans.get(i));        }        return ans2;    }}



0 0
原创粉丝点击