[C#][LeetCode][Easy] 104. Maximum Depth of Binary Tree

這題是典型的遞迴題目,題目要求找到二元樹最深的層級為多少。

這題的解法很簡單,先宣告兩個變數分別來儲存左邊與右邊的層級,首先判斷左邊是否為空,若非為空值則會繼續搜尋此節點的子節點是否為空,搜尋完畢後再一併回傳至第一層的left變數裡,右邊反之,最後在比較左右兩邊哪個最大,最大的數字即為二元樹的層級。

Read More

[C#] 基礎複習 – 遞迴練習

好久沒用遞迴了,趕快找個簡單的題目複習一下,不然都要忘光光了,熟悉一下之前的Feel ~
順便練習一下簡單工廠模式,首先設計介面ICompute.cs

interface ICompute
{
    /// <summary>
    /// 1 + ... + N = ?
    /// </summary>
    /// <param name="n"></param>
    /// <returns>Answer</returns>
    Int64 Iterative(Int64 n);

    /// <summary>
    /// 1 - 2 + 3 ... + N = ?
    /// </summary>
    /// <param name="n"></param>
    /// <returns>Answer</returns>
    Int64 AdvancedIterative(Int64 n);

    /// <summary>
    /// 1 x 2 x ... x N = ?
    /// </summary>
    /// <param name="n"></param>
    /// <returns>Answer</returns>
    Int64 Factorial(Int64 n);

    /// <summary>
    /// Fn = Fn-1 + Fn-2
    /// </summary>
    /// <param name="n"></param>
    /// <returns>Answer</returns>
    Int64 Fibonacci(Int64 n);
}

Read More