java dfs实现:
/**
* dfs实现
*
* @param root
* @return
*/
public List<List<Integer>> levelOrderDfs(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
_dfs(res, root, 0);
return res;
}
void _dfs(List<List<Integer>> res, TreeNode node, int level) {
if (node == null) return;
if (res.size() < level + 1) res.add(new ArrayList<>());
res.get(level).add(node.val);
_dfs(res, node.left, level + 1);
_dfs(res, node.right, level + 1);
}
作者回复: Cool!
2019-03-26
joy
DFS Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
levelHelper(res, root, 0);
return res;
}
public void levelHelper(List<List<Integer>> res, TreeNode node, int level) {
if (node == null) return;
if (res.size() < level + 1) {
res.add(new ArrayList<>());
}
res.get(level).add(node.val);
levelHelper(res, node.left, level + 1);
levelHelper(res, node.right, level + 1);
}
}
作者回复: Nice work
2019-03-25
棒棒彬👻
没有用 Swift 来写的小伙伴么?
BFS,广度优先,算法复杂度 O(n) (Swift)
```swift
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func levelOrder(_ root: TreeNode?) -> [[Int]] {
guard let root = root else { return [] }
var result: [[Int]] = []
var queue: [TreeNode] = []
queue.append(root)
while !queue.isEmpty {
let levelSize = queue.count
var currentLevel: [Int] = []
for _ in 0 ..< levelSize {
let node = queue.removeFirst()
currentLevel.append(node.val)
if let left = node.left {
queue.append(left)
}
if let right = node.right {
queue.append(right)
}
}
result.append(currentLevel)
}
return result
}
}
```
作者回复: Cool!
2019-03-17
Derek
GO语言版本实现:
func levelOrder(root *TreeNode) [][]int {
var result [][]int
if root == nil {
return result
}
visited := make(map[int]int)
queue := list.New()
queue.PushBack(root)
for queue.Len() > 0 {
var curLevel []int
count := queue.Len()
for count > 0 {
element := queue.Front()
node := element.Value.(*TreeNode)
if _, exist := visited[node.Val]; exist {
continue
}
visited[node.Val]++
curLevel = append(curLevel, node.Val)
if node.Left != nil {
queue.PushBack(node.Left)
}
if node.Right != nil {
queue.PushBack(node.Right)
}
queue.Remove(element)
count--
}
result = append(result, curLevel)
}
return result
}