二叉树的最大深度
二叉树的最大深度,一层一层遍历下来,首先想到的是while循环,可是在写的过程中发现写不下去,没办法做到累加,也没办法做到左子树与右子树最大深度的比较。
之后想到递归,但是没有思路,发愁。。。
看了官方题解之后,整理了一下思路:
1、使用递归。
2、递归中的最终点是子节点为null,此时返回0。
3、因为为null的子节点的父节点不为null,所以此时需要给深度+1。
4、使用Math.max(a,b)获得左子树与右子树的最大深度。
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
}
二叉树的层序遍历
每次看官方的思路都感觉不像是在说人话。。。只能看题解才能看懂。
思路:因为是层序遍历,所以需要取出二叉树所有的层,而且每一层需要从左到右,下一层的元素也是从左到右,那么应该是在遍历第K层元素的时候,将K+1层的元素也取出,加入到队列末尾,由FIFO的特性来管理队列。
需要注意的是:在遍历每一层的时候,此时这一层元素的个数与队列长度相等,在遍历时又不断向队列中增加新的元素,所以需要提前将队列长度赋值给一个变量。
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> list = new ArrayList<Integer>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
result.add(list);
}
return result;
}
}
二叉树的层序遍历II
这道题与上一个题很类似,思路也基本相同,但是它的结果是需要从最底层的子节点开始,到根节点结束。最终结果与上一题的结果完全相反,第一反应是使用reverse(),哈哈哈哈~~~
上一题使用了ArrayList作为最终结果的List,这里可以使用LinkedList,因为它在add元素的时候使用add(index,T)可以提高效率。
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> list = new ArrayList<Integer>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
result.add(0, list);
}
return result;
}
}
今天就到这啦~~~