美文网首页
226. Invert Binary Tree (E)

226. Invert Binary Tree (E)

作者: Ysgc | 来源:发表于2020-11-24 11:05 被阅读0次

    Invert a binary tree.

    Example:

    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.


    /**
     * 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) return root;
            TreeNode* temp = root->left;
            root->left = root->right;
            root->right = temp;
            invertTree(root->left);
            invertTree(root->right);
            return root;
        }
    };
    

    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Invert Binary Tree.
    Memory Usage: 9.7 MB, less than 20.00% of C++ online submissions for Invert Binary Tree.

    注意事项:

    • 要判断root或者某个recursion的input是否是null
    • 要记得return

    相关文章

      网友评论

          本文标题:226. Invert Binary Tree (E)

          本文链接:https://www.haomeiwen.com/subject/drbriktx.html