Invert a binary tree.
Example:
1 |
|
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
Related Topics: Hash Table
解題邏輯與實作
頗為知名的一題(笑),但基本上沒什麼難度,只需要互換節點左右兩邊的子樹即可。
遞迴
實作上就是採用後序(post-order)的方式尋訪整棵樹,並在尋訪父節點時交換左右子樹。
1 |
|
最速解
我寫這篇就是為了分享這個,在 Ruby China 上看到如何用最少字元翻轉二元樹XDDDDD
1 |
|