[LeetCode] 226. Invert Binary Tree

我们学过树的前序遍历(DFS)和层次遍历(BFS),在邓俊辉《数据结构(C++语言版)》的前序遍历和层次遍历的实现里,访问节点的步骤叫visit,它是一个作为参数传入的函数,也叫做高阶函数
在本题中,既然要反转整棵树,那就是要遍历。遍历做什么事情?交换一个节点的左右孩子。既然visit是访问节点的函数,“交换一个节点的左右孩子”是对节点的操作,因此我们可以把它看作是visit。于是答案也就呼之欲出了:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

// BFS version
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        queue q;
        q.push(root);
        while (!q.empty()) {
            TreeNode* node = q.front();
            q.pop();
            if (node) {
                // visit
                std::swap(node->left, node->right);
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
        }
        return root;
    }
};

// DFS version
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == nullptr) {
            return nullptr;
        }
        // visit
        std::swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

你可能感兴趣的:([LeetCode] 226. Invert Binary Tree)