104. 二叉树的最大深度
状态:完成
思路:使用前序遍历的方式求得二叉树的最大深度,每次递归比较左右节点哪个更加大再加上当前节点(+1),最后得到二叉树最大深度。用层序遍历昨天已经实现过了。
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
return dfs(root);
}
public int dfs(TreeNode root){
if(root==null){
return 0;
}
int left = dfs(root.left);
int right= dfs(root.right);
return left>right?left+1:right+1;
}
}
559. N 叉树的最大深度
状态:完成
思路:把上一题对比左右节点的过程换成在children里找最大的过程。
class Solution {
public int maxDepth(Node root) {
if(root==null) return 0;
List<Node> list = root.children;
int max=0;
for(Node node:list){
int temp=maxDepth(node);
max=max>temp?max:temp;
}
return max+1;
}
}
111. 二叉树的最小深度
状态:完成
思路:用层序遍历当遍历到左右节点都是空的时候到达底部。也可以用前序遍历和后序遍历去做。
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
int index=0;
while(queue.size()>0){
int size=queue.size();
for(int i=0;i<size;i++){
TreeNode node= queue.poll();
if(node.left!=null) queue.add(node.left);
if(node.right!=null) queue.add(node.right);
if(node.left==null&&node.right==null){
return index+1;
}
}
index++;
}
return index;
}
}
前序遍历做法,这里要注意跟最大深度不同的就是当左右节点中有一个节点是null时不能取这个节点的深度要去另一个节点的深度,因为等于null是不存在的,没有深度等于0的二叉树。
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
int left =minDepth(root.left);
int right =minDepth(root.right);
System.out.println(Math.min(left,right));
return left!=0&&right!=0?Math.min(left,right)+1:Math.max(left,right)+1;
}
}
222. 完全二叉树的节点个数
状态:一一个个遍历的方式可以做但是下面这种利用完全二叉树性质的方式没有想出来
思路:完全二叉树可以拆成一个个完全二叉树的集合,如果左右节点遍历之后不相等说明这个子树不是完全二叉树,所以遍历这个节点的左右子树直到得到完全二叉树子树为止,相加得到最后结果。
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
TreeNode node = root;
int left=0;
int right=0;
while(node!=null){
node=node.left;
left++;
}
node=root;
while(node!=null){
node=node.right;
left++;
}
if(left==right){
return (2<<left)-1;
}
return countNodes(root.left)+countNodes(root.right)+1;
}
}