leetcode(226)—— Invert Binary Tree(Python/C++)

Invert Binary Tree

二叉树节点定义:

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 || (!root->left && !root->right))
            return root;

        TreeNode *tmp = root->left;
        root->left = root->right;
        root->right = tmp;

        root->left = invertTree(root->left);
        root->right = invertTree(root->right);
        return root;
    }
};

法2:使用迭代(借助队列)

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {

        if (!root)
            return root;

        queue que;
        que.push(root);

        while (!que.empty()){
            TreeNode *node = que.front();
            que.pop();

            TreeNode *tmp = node->left;
            node->left = node->right;
            node->right = tmp;

            if (node->left)
                que.push(node->left);
            if (node->right)
                que.push(node->right);
        }
        return root;
    }
};

你可能感兴趣的:(leetcode)