一102:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
题目
思路:层次遍历,就一层层遍历,先将根节点入队,然后根据目前队列的大小,来进行几次入队出队操作(看代码,会有注释)
代码:
二:107:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
题目:
思路:同上题一摸一样,最后将结果reverse即可
代码:
三:429:https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/
题目:
思路:依旧是层次遍历,只不过这个children更多,因此注意表达式即可,多做这种自定义的题就可以了
代码:
四:637:https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
题目:
思路:层次遍历,注意结果是double型即可
总结:以上四题,层次遍历,因为他对输出有一定要求,差不多就是,要一层层的输入,因此在遍历时会偶有对一层层进行控制。
代码:
五:314 https://leetcode-cn.com/problems/binary-tree-vertical-order-traversal/
题目:
思路:其实说是层次遍历,也想BFS,差不多的思想,这题乍看奇怪,其实从根节点开始,以它为坐标原点,左孩子坐标-1,右孩子坐标就+1,然后用map来从高往低存储,高往低,也就是层次遍历的顺序。
代码:
收获:刚开始没想到直接用层次遍历就可以直接从高往低的存入数据了,所以后来还要排序,比较麻烦,用层次遍历清晰明了。
六:993:https://leetcode-cn.com/problems/cousins-in-binary-tree/
题目:
思路:首先必须满足两者的深度相等,再判断其父节点,只要父节点不同,则定符合题意,因此dfs遍历,同时用map存储,当前结点,深度,父节点。
代码:
七:111:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
题目:
思路:递归,每一层加一,但是在某个结点只有一个孩子时,需要返回那个有孩子的深度,不然最小深度永远为0;
代码: