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

数据结构复习--binary tree level-order traversal

时间:2014-11-25 17:52:34      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:io   ar   sp   for   数据   on   bs   ad   ef   

一个笨办法用两个Queue实现:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if(root==null)
            return new ArrayList<List<Integer>>();
         
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Queue<TreeNode> tmp1 = new ArrayDeque<TreeNode> ();
        Queue<TreeNode> tmp2 = new ArrayDeque<TreeNode> ();
        tmp1.add(root);
        boolean check = true;
        while (!tmp1.isEmpty() || !tmp2.isEmpty()){
            List<Integer> row = new ArrayList<Integer>();
            if(check)
            {
                while(!tmp1.isEmpty()){
                    TreeNode top = tmp1.remove();
                    row.add(top.val);
                    if(top.left!=null)
                        tmp2.add(top.left);
                    if(top.right!=null)
                        tmp2.add(top.right);
                }
                check = false;
                 
            }
            else{
                while(!tmp2.isEmpty()){
                    TreeNode top = tmp2.remove();
                    row.add(top.val);
                    if(top.left!=null)
                        tmp1.add(top.left);
                    if(top.right!=null)
                        tmp1.add(top.right);
                }
                check = true;
            }
            result.add(0,row);
        }
        return result;
    }
}

 

一个聪明的办法DFS:

public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if(root==null)
            return new ArrayList<List<Integer>>();
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        result.add(new ArrayList<Integer>());
        DFS(result,root,0);
        return result;
    }
     
    public void DFS(List<List<Integer>> result, TreeNode root, int level){
        if(root==null)
            return;
        if(level==result.size())
            result.add(0,new ArrayList<Integer>());
        result.get(result.size()-1-level).add(root.val);
        DFS(result, root.left, level+1);
        DFS(result, root.right, level+1);
    }
}

数据结构复习--binary tree level-order traversal

标签:io   ar   sp   for   数据   on   bs   ad   ef   

原文地址:http://www.cnblogs.com/cs-jack-cheng/p/4121311.html

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