码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode 107.Binary Tree Level Order Traversal II (二叉树水平序)

时间:2015-08-01 22:07:00      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二叉树   遍历   dfs   

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

思路:此题和二叉树水平序类似,求解水平序之后再反转下链表即可。代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<List<Integer>> list;
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        list = new ArrayList<List<Integer>>();
        //对list进行倒序排序
        dfs(0,root);
        
        for(int i = 0; i+i < list.size()-1;i++){
            List<Integer> al = list.get(i);
            list.set(i,list.get(list.size()-1-i));
            list.set(list.size()-1-i,al);
        }
        return list;
    }
    
    private void dfs(int dep,TreeNode root){
        if(root == null){
            return;
        }
        List<Integer> al;
        if(list.size() > dep){
            al = list.get(dep);
        }else{
            al = new ArrayList<Integer>();
            list.add(al);
        }
        
        dfs(dep+1,root.left);
        al.add(root.val);
        dfs(dep+1,root.right);
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetCode 107.Binary Tree Level Order Traversal II (二叉树水平序)

标签:leetcode   二叉树   遍历   dfs   

原文地址:http://blog.csdn.net/xygy8860/article/details/47189679

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!