[LeetCode] Invert Binary Tree

Invert Binary Tree

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:

解题思路:

用递归解即可。先将以左孩子节点为根节点的子树翻转,然后将以右孩子节点为根节点的子树翻转,然后交换一下根节点的左右子树。

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


你可能感兴趣的:(LeetCode,C++)