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

Binary Tree Level Order Traversal II

时间:2015-06-29 15:02:29      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:leetcode   tree   

原题如下:
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).

技术分享

我的算法:
1. 首先获得树的高度
2. 层序递归遍历二叉树(从左到右)

实现如下:

package leetCode;

import java.util.ArrayList;
import java.util.List;

public class Solution {

    //获得二叉树的高度,采用递归算法,简单实用
    int depth(TreeNode root){
        int res = 0;
        if(root==null){
            return 0;
        }
        int l = depth(root.left);
        int r = depth(root.right);
        res = Math.max(l, r)+1;
        return res;
    }

    //当前层的高度为level,采用递归算法,简单实用,list为最终的结果list,
    //list作参数(java对象作为参数),可以看做是引用传递,在方法中对list修改,能
    //影响最终的list
    void levelOrder(TreeNode root,int level,List<List<Integer>> list){

        if(root==null){
            return;
        }

        int toIndex = list.size()-1;
        list.get(toIndex-level).add(root.val);

        //从左到右递归层序递归遍历二叉树
        levelOrder(root.left,level+1,list);
        levelOrder(root.right,level+1,list);
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
        int dep = depth(root);

        for(int i=0;i<dep;i++){
            ArrayList<Integer> t = new ArrayList<Integer>();
            res.add(t);
        }

        levelOrder(root,0,res);

        return res;
    }

    public static void main(String[] args) {
        TreeNode t = TreeNode.getDefaultTree();
        List<List<Integer>> res = new ArrayList<List<Integer>>();

        Solution s = new Solution();
        res = s.levelOrderBottom(t);

        for(int i=0;i<res.size();i++){
            System.out.println(res.get(i));
        }   
    }
}

TreeNode的代码如下:

package leetCode;

public class TreeNode {

    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
    //获得一颗默认的树,跟上面题中一样
    public static TreeNode getDefaultTree(){
        TreeNode t1 = new TreeNode(3);
        TreeNode t2 = new TreeNode(9);
        TreeNode t3 = new TreeNode(20);
        TreeNode t4 = new TreeNode(15);
        TreeNode t5 = new TreeNode(7);

        t1.left = t2;
        t1.right = t3;
        t3.left = t4;
        t3.right = t5;

        return t1;
    }
}

原题地址:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/

Binary Tree Level Order Traversal II

标签:leetcode   tree   

原文地址:http://blog.csdn.net/x_i_y_u_e/article/details/46680367

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