码迷,mamicode.com
首页 > 编程语言 > 详细

Binary Tree Level Order Traversal - leetcode - java

时间:2015-12-18 10:31:49      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

DFS实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    // DFS 遍历
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        traverse(res, root, 0);
        return res;
    }

    public void traverse(List<List<Integer>> res, TreeNode root, int level) {
        if (root == null) {
            return;
        }
        if (res.size() > level) {
            res.get(level).add(root.val);
        } else {
            ArrayList list = new ArrayList<Integer>();
            list.add(root.val);
            res.add(list);
        }
        traverse(res, root.left, level + 1);
        traverse(res, root.right, level + 1);
    }
    

}

 

BFS实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    // BFS遍历打印
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        if (root == null)
            return res;
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        ArrayList<Integer> list = new ArrayList<Integer>();
        int cur = 1;
        int nextLevel = 0;
        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();

            cur--;
            if (tmp.left != null) {
                queue.add(tmp.left);
                nextLevel++;
            }
            if (tmp.right != null) {
                queue.add(tmp.right);
                nextLevel++;
            }
            list.add(tmp.val);
            if (cur == 0) {
                res.add(list);
                list = new ArrayList<Integer>();
                cur = nextLevel;
                nextLevel = 0;
            }

        }
        return res;
    }

}

 

Binary Tree Level Order Traversal - leetcode - java

标签:

原文地址:http://www.cnblogs.com/tina-smile/p/5056199.html

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