226.leetcode Invert Binary Tree(easy)[二叉树 递归]

来源:互联网 发布:家用除尘设备知乎 编辑:程序博客网 时间:2024/04/20 00:54

Invert a binary tree.

     4   /   \  2     7 / \   / \1   3 6   9
to
     4   /   \  7     2 / \   / \9   6 3   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 fuck off.

题目的含义是得到左子树与右子树交换的树,那么按照树的递归方式分别交换每个节点的左右子树即可。

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


0 0
原创粉丝点击