Leetcode226
1.问题描述
2.解决方案
整体思路呢不必多说,就是遍历整棵二叉树,对每一个节点的左右孩子一交换就完事,所以不同的实现方法只是遍历方式不同罢了,前序后序层序都可以,但是中序不可以(中序会把结点反转两次),这里只给出一种递归前序的代码实现
class Solution {
public:
void invert(TreeNode* root){
if(root== nullptr) return;
swap(root->left,root->right);
invert(root->left);
invert(root->right);
}
TreeNode* invertTree(TreeNode* root) {
invert(root);
return root;
}
};