Leetcode|二叉树的修改与构造|226. 翻转二叉树

2021-09-18 15:25:04 浏览数 (1)

1 分治法-递归

代码语言:javascript复制
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
       if (!root) return nullptr;
       swap(root->left, root->right);
       invertTree(root->left);
       invertTree(root->right);
       return root;
    }
};

2 BFS

代码语言:javascript复制
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
       if (!root) return nullptr;
       queue<TreeNode*> q;
       q.push(root);
       TreeNode* node = new TreeNode(root->val);
       while (!q.empty()) {
           int sz = q.size();
           for (int i=0;i < sz;i  ) {
               TreeNode* e_ptr = q.front(); q.pop();
               swap(e_ptr->left, e_ptr->right);
               if (e_ptr->right) q.push(e_ptr->right);
               if (e_ptr->left) q.push(e_ptr->left);
           }
       }
       return root;
    }
};

0 人点赞