思路分析
递归思路
- 需要先求出左子树深度和右子树深度,之后再求根节点深度,所以递归遍历时,采用后序遍历。
 
- 在求出左子树和右子树深度后,取他们中的最大值作为子树的深度,之后用子树的深度加1即可得树的深度。
 
import java.util.*;
/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */
public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if(root == null)
            return 0;
        int left = maxDepth(root.left);  // 求左子树深度
        int right = maxDepth(root.right); // 求右子树深度
        return left > right ? (left + 1) : (right + 1); // 根的深度
    }
}