Binary Tree Level Order Traversal

题目描述:

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]
]
层次遍历用队列解决。注意一点是用一个level来存储层次信息,代码如下:

class Node{
	int level;
	TreeNode treenode;
	public Node(int level,TreeNode treenode){
		this.level = level;
		this.treenode = treenode;
	}
}
 
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		if(root == null)
			return result;
		ArrayDeque<Node> queue = new ArrayDeque<Node>();
		queue.add(new Node(1, root));
		while(!queue.isEmpty()){
			Node node = queue.pop();
			if(node.level>result.size()){
				List<Integer> list = new ArrayList<Integer>();
				list.add(node.treenode.val);
				result.add(list);
			}else
				result.get(node.level-1).add(node.treenode.val);
			if(node.treenode.left!=null)
				queue.add(new Node(node.level+1,node.treenode.left));
			if(node.treenode.right!=null)
				queue.add(new Node(node.level+1,node.treenode.right));
		}
		return result;
    }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yeshiwu/article/details/51565337
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭