The maximum depth LineCode97. Binary Tree

description

Given a binary tree to find its maximum depth.

The depth of the binary tree leaf nodes to the root node to the farthest distance.

Have you encountered this problem in a real interview?
Sample
Sample 1:

Input: tree = {}
Output: 0
Sample Explanation: 0 is the depth of an empty tree.
Sample 2:

Input: tree = {1,2,3, #, #, 4,5}
Output: 3
Sample Explanation: tree follows a depth of 3
1
/ \
23
/ \
45
it will be serialized as {1 , 2,3, #, #, 4,5}

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    public int maxDepth(TreeNode root) {
        // write your code here
             if (root == null) {
            return 0;
        }

        int resLeft = maxDepth(root.left) + 1;
        int resRight = maxDepth(root.right) + 1;
        return Math.max(resLeft, resRight);
    }
}

Guess you like

Origin blog.csdn.net/leohu_v5/article/details/91818712