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;
}
};
原创文章,作者:306829225,如若转载,请注明出处:https://blog.ytso.com/275333.html