LeetCode 226 Invert Binary Tree

197 阅读1分钟

LeetCode 226 Invert Binary Tree

思路

递归

可分为从上至下与从下往上两种方法

迭代

可分为深度优先与广度优先。对树按一层层的遍历,采用队列。深度优先则采用栈。

代码

递归 从上至下

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return nullptr;
        
        invertTree(root, root->left, root->right);
        
        return root;
    }
    
    void invertTree(TreeNode* root, TreeNode *left, TreeNode *right) {
        if (left && right) {
            root->left = right;
            root->right = left;
            invertTree(left, left->left, left->right);
            invertTree(right, right->left, right->right);
        }
        else if (!left && right) {
            root->left = right;
            root->right = nullptr;
            invertTree(right, right->left, right->right);
        }
        else if (left && !right) {
            root->right = left;
            root->left = nullptr;
            invertTree(left, left->left, left->right);
        }
    }
};

递归 从下往上

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return nullptr;
        
        invertTree(root->left);
        invertTree(root->right);
        
        TreeNode *temp = root->left;
        root->left = root->right;
        root->right = temp;
        
        return root;
    }
};

迭代 DFS

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return nullptr;
        
        stack<TreeNode*> stk;
        stk.push(root);
        
        while (!stk.empty()) {
            TreeNode *cur = stk.top();
            stk.pop();
            
            TreeNode *temp = cur->left;
            cur->left = cur->right;
            cur->right = temp;
            
            if (cur->left)
                stk.push(cur->left);
            if (cur->right)
                stk.push(cur->right);
        }
        
        return root;
    }
};

迭代 BFS

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return nullptr;
        
        queue<TreeNode*> qu;
        qu.push(root);
        
        while (!qu.empty()) {
            TreeNode *cur = qu.front();
            qu.pop();
            TreeNode *temp = cur->left;
            cur->left = cur->right;
            cur->right = temp;
            
            if (cur->left) 
                qu.push(cur->left);
            if (cur->right)
                qu.push(cur->right);
        }
        
        return root;
    }
};