LeetCode 226 Invert Binary Tree DFS
Given the root
of a binary tree, invert the tree, and return its root
.
Solution:
直接使用 \(DFS\) 进行递归即可:
点击查看代码
/**
* 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 {
private:
void dfs(TreeNode* root){
if(!root)return;
swap(root->right, root->left);
dfs(root->right);dfs(root->left);
}
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL) return NULL;
dfs(root);
return root;
}
};