226. Invert Binary Tree(要多看)

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

解法二:层次遍历

/**
 * 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 root;
        queue q;
        q.push(root);
        while(!q.empty()){
            TreeNode * cur = q.front();
            q.pop();
            swap(cur->left, cur->right);
            if(cur->left) q.push(cur->left);
            if(cur->right) q.push(cur->right);
        }
        return root;
    }
};

你可能感兴趣的:(226. Invert Binary Tree(要多看))