瀏覽標籤:

遞迴

[C#][LeetCode][Easy] 226. Invert Binary Tree

心得:

這題也是典型的遞迴,題目要求把二元樹整個翻轉過來。

問題:

Invert a binary tree.

to

答案:

  1. 遞迴

     
       

[C#][LeetCode][Easy] 258. Add Digits

心得:

題目要求將每一位數相加,直到剩下個位數。

問題:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

答案:

  1. For + 遞迴
  2. LinQ + 遞迴
  3. Normal
       

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

心得:

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

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

問題:

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.

答案:

參考:

  1. https://skyyen999.gitbooks.io/-leetcode-with-javascript/content/questions/104md.html
       

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

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

接著建立兩個類別Recursive.csForLoop.cs並繼承ICompute.cs實作其方法:

  • Recursive.cs
  • ForLoop.cs

接著在Program.cs裡面寫一個Run的方法來呼叫剛剛寫好的兩個類別:

這樣就完成囉 !!

2017-01-05-20_15_29-file____c__users_developer_documents_recursiveeample_recursiveeample_recursiveea

 

原始碼:https://github.com/shuangrain/RecursiveEample