LeetCode -- Binary Tree Level Order Traversal
2015-09-22 09:49
323 查看
题目描述:
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]
]
本题考查基本的BFS算法,把逐层遍历的节点添加到结果集中。
实现代码:
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]
]
本题考查基本的BFS算法,把逐层遍历的节点添加到结果集中。
实现代码:
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public IList<IList<int>> LevelOrder(TreeNode root) { if(root == null){ return new List<IList<int>>(); } var starts = new List<TreeNode>(); if(root.left != null){ starts.Add(root.left); } if(root.right != null){ starts.Add(root.right); } var result = new List<IList<int>>(); result.Add(new List<int>(){root.val}); Travel(starts, result); return result; } public void Travel(IList<TreeNode> parents, IList<IList<int>> result) { // stop if(parents == null || parents.Count == 0){ return ; } // add previous level nodes result.Add(parents.Select(x=>x.val).ToList()); // get each parent childs and combine, do BFS var children = new List<TreeNode>(); foreach(var n in parents){ var nodes = Children(n); //add children children.AddRange(nodes); } Travel(children, result); } private IList<TreeNode> Children(TreeNode n) { var nodes = new List<TreeNode>(); if(n.left != null){ nodes.Add(n.left); } if(n.right != null){ nodes.Add(n.right); } return nodes; } }
相关文章推荐
- 我的Android进阶之旅------>adbd cannot run as root in production builds 的解决方法
- Tomcat 并发一些问题
- 用JS关闭带框架的窗口(转自百度知道)
- How to configure Eclipse for Python programming
- Formatting is Specified but argument is not IFormattable
- 多条记录的同一字段组合成一个字符串 FOR XML PATH
- 9.22问题总结
- LeetCode -- Basic Caculator
- 【TCP】TCP连接建立过程的三次握手
- URAL 1009 K-based Numbers (DP动态规划)
- 线性表
- jQuery权限控制
- Centos6.x PPTPD 搭建方法,亲测有效
- HDU 3648 Median Filter
- 【转】C# 流总结
- 解决更新Xcode以后使用Git报错的问题
- js 让小数四舍五入保留两位小数的函数是?
- 玩node-images模块---Node.js轻量级跨平台图像编解码库
- Android开发总结笔记 TableLayout(表格布局) 1-1-4
- less的使用