Try   HackMD

【LeetCode】 226. Invert Binary Tree

Description

Invert a binary tree.

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.

反轉一顆二元樹。

小知識:
這道題目發想自Max Howell的一篇推特
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

/** * 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++