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

8.2 leetcode 102,107. binary tree level order traversal I & II:(up-down & bottom-up)

时间:2015-08-04 07:04:20      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

 1 public class Solution {
 2     public List<List<Integer>> levelOrder(TreeNode root) {
 3          List<List<Integer>> res = new ArrayList<List<Integer>>();
 4          if(root == null) return res;
 5          Queue<TreeNode> q = new LinkedList<TreeNode>();
 6          q.add(root);
 7          int level = 0;
 8          while(! q.isEmpty()) {
 9              res.add(new ArrayList<Integer>()); // Important or res does not have space to hold data
10              int curSize = q.size();
11              for(int i = 0; i < curSize; i++) { // remove all nodes in this level
12                  TreeNode temp = q.remove();
13                  res.get(level).add(temp.val);
14                  if(temp.left != null) q.add(temp.left);
15                  if(temp.right != null) q.add(temp.right);  
16              }
17              level++;
18          }
19          return res;
20     }
21 }

Traversal II:

public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>(); // IMPORTANT: change the second ArrayList to List.
        if (root == null) return ans;
        LinkedList<TreeNode> q = new LinkedList<TreeNode>();
        q.add(root);
        while (! q.isEmpty()) {
            ans.add(0, new ArrayList<Integer>());
            int curSize = q.size();
            for (int i = 0; i < curSize; i ++) {
                TreeNode node = q.remove();
                ans.get(0).add(node.val);
                if (node.left != null) q.add(node.left);
                if (node.right != null) q.add(node.right);
            }
        }
        return ans;
    }
}

 

8.2 leetcode 102,107. binary tree level order traversal I & II:(up-down & bottom-up)

标签:

原文地址:http://www.cnblogs.com/michael-du/p/4700888.html

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