LC 二叉树的最大深度

LC 二叉树的最大深度

思路: 比较左子树和右子树的高度,选最大的那个,然后递归。 

代码:

/**
 * 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);
        if (leftdepth > rightdepth) {
            return 1 + leftdepth;
        }
        else {
            return 1 + rightdepth;
        }
    }
}

上一篇:Exception: Timeout while feeding partition


下一篇:剑指 Offer 37. 序列化二叉树