104. 二叉树的最大深度https://leetcode.cn/problems/maximum-depth-of-binary-tree/
给定一个二叉树
root
,返回其最大深度。二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:3
算法思想
下面给出BFS思想算法,递归算法不再给出;将每一层的所有元素放到queue中,ans++;
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
Queue<TreeNode> queue=new LinkedList<>();
int ans=0;
queue.offer(root);
while(!queue.isEmpty()){
int size=queue.size();
while(size>0){
TreeNode tmp=queue.poll();
if(tmp.left!=null){
queue.offer(tmp.left);
}
if(tmp.right!=null){
queue.offer(tmp.right);
}
size--;
}
ans++;
}
return ans;
}
}
94. 二叉树的中序遍历https://leetcode.cn/problems/binary-tree-inorder-traversal/
给定一个二叉树的根节点
root
,返回 它的 中序 遍历 。示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]
算法思想
递归
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
inorder(root,res);
return res;
}
public void inorder(TreeNode root, List<Integer> res){
if(root==null){
return;
}
inorder(root.left,res);
res.add(root.val);
inorder(root.right,res);
}
}