# 【LeetCode】 226. Invert Binary Tree ## Description > Invert a binary tree. > Trivia: > This problem was inspired by [this original tweet](https://twitter.com/mxcl/status/608682016205344768) by [Max Howell](https://twitter.com/mxcl): 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. > 反轉一顆二元樹。 > 小知識: > 這道題目發想自[Max Howell](https://twitter.com/mxcl)的一篇[推特](https://twitter.com/mxcl/status/608682016205344768): > Google:我們90%的工程師都在使用你寫的軟體(Homebrew),但是你不會在白板上寫出反轉二元樹所以滾出去。 > (簡單來說,開發Homebrew的作者Max Howell以前曾應徵過google但沒過面試,後來在推特上發文諷刺白板題的重要性XD) ## Example: ``` Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 ``` ## Solution * 很基本的樹結構題目,沒什麼需要特別說的。 * 把左右子樹交換(可以自己寫也可以直接使用內建的`swap()`),然後遞迴呼叫左右子樹,直到自己是`null`停止。 ### Code ```C++=1 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root) { swap(root->left, root->right); invertTree(root->left); invertTree(root->right); } return root; } }; ``` ###### tags: `LeetCode` `C++`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up