LeetCode 226. Invert Binary Tree (Easy)

来源:互联网 发布:澳洲传媒硕士 知乎 编辑:程序博客网 时间:2024/04/18 11:05

题目描述:

Invert a binary tree.

Example:

     4   /   \  2     7 / \   / \1   3 6   9                to     4   /   \  7     2 / \   / \9   6 3   1

题目大意:反转二叉树。

思路:递归,直接交换。
主要是题目里这个比较搞笑:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
大概意思是说写出Homebrew的老哥因为不会反转二叉树而被google拒了。

c++代码:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* invertTree(TreeNode* root) {        if (root == nullptr)            return root;        auto temp = root->left;        root->left = root->right;        root->right = temp;        invertTree(root->left);        invertTree(root->right);        return root;    }};