题目描述
Invert a binary tree.
递归版本解题思路
- 如果当前节点为空, 为本层递归结束的标志
- 当前节点的左右子树进行互换位置
- 分别对当前节点的左子树,右子树进行翻转
- 返回root即可
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL){
return root;
}
if(root -> left != NULL || root -> right != NULL){
TreeNode* t = root -> left;
root -> left = root -> right;
root -> right = t;
}
if(root -> left){
invertTree(root -> left);
}
if(root -> right){
invertTree(root -> right);
}
return root;
}
};