思路:递归,DFS或者BFS层次遍历
递归版本
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
// 左子树高度
int leftHeight = maxDepth(root.left);
// 右子树高度
int rightHeight = maxDepth(root.right);
// 返回高度较高的子树+1
return Math.max(leftHeight, rightHeight) + 1;
}
}
}
DFS
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left+1, right+1);
}
}
BFS层次遍历
class Solution {
public int maxDepth(TreeNode root) {
LinkedList<TreeNode> queue = new LinkedList<>();
if (root == null) return 0;
queue.add(root);
int depth = 0;
while (!queue.isEmpty()){
depth++;
int size = queue.size();
// 注意不要for (int i = 0; i < queue.size(); i++),因为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);
}
}
return depth;
}
}