解(C++):
1.二叉树判空 if(root == 0) 或 if(root == nullptr);
2.二叉树的左子树: root->left .
3.使用递归,将当前根节点的左右指针指向互换左向右子树(此时右子树也进行了翻转)
// C++
/*** 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 == 0)return root;TreeNode* temp = root->left;root->left = invertTree(root->right);root->right = invertTree(temp);return root;}
};
解(JavaScript): 每次对根做处理,若根非空,判断左右子树是否全为空,若有一个不为空,交换左右子树的指向,并翻转左右子树
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*/
/*** @param {TreeNode} root* @return {TreeNode}*/
var invertTree = function(root) {if(root){if(root.left || root.right) {var l = root.left;var r = root.right;root.right = l;root.left = r;invertTree(l);invertTree(r);}return root;
};