二叉树---反转二叉树,也就镜像二叉树

1、题目:

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

2、解答:无

3、C++代码

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
      if(root){
          swap(root->left,root->right);
          invertTree(root->left);
          invertTree(root->right);
          //root->left = invertTree(root->right);
          //root->right = invertTree(root->left);
          
      }
     return root;
    }
};

python代码:

class Solution:
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root:
            root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)
        return root

猜你喜欢

转载自blog.csdn.net/qq_31307013/article/details/80307780