一、深度优先搜索
Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
int leftDepth=maxDepth(root.left);
int rightDepth=maxDepth(root.right);
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
}
二、广度优先搜索,按层次搜