LeetCode BFS(上)
这里是LeetCode BFS类型前半部分题目:
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Clone Graph
#1.Binary Tree Zigzag Level Order Traversal ref
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example: Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
zigzag遍历很简单,但是我封装了TreeNode,新造了一个数据结构ZigZag来保存每一个节点的层次,不够优雅,有没有什么方法不用封装呢,看下面。
#2.Binary Tree Level Order Traversal ref
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]
]
这里用pair<TreeNode*, int>来封装TreeNode,和新定义一个struct差不多,不过程序看起来更优美了。
#3.Binary Tree Level Order Traversal II ref
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
For example: Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
] 将[Binary Tree Level Order Traversal ](#ch2)返回的数组reverse一下就可以了。
#4.Clone Graph
在DFS系列里已经解决了这个问题==Clone Graph
留下评论