【LeetCode】#104 Maximum Depth of Binary Tree(C#)

● 問題

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

● 思考點

求出節點左、右葉子值(最大值),接著加一即求出。

● Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
 
public class Solution {
    public int MaxDepth(TreeNode root) {
        if (root == null) return 0;
        var leftDepth = MaxDepth(root.left) + 1;
        var rightDepth = MaxDepth(root.right) + 1;
        return (leftDepth > rightDepth) ? leftDepth : rightDepth;
    }
}