56.翻转二叉树

 

递归

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return root;
        }
        TreeNode temp=root.left;
        root.left=root.right;
        root.right=temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
}
class Solution(object):
    def invertTree(self, root):
        if root is None:
            return root
        root.left,root.right=root.right,root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

 迭代

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return root;
        }
        Queue<TreeNode> qu=new LinkedList<>();
        TreeNode tn;
        int le;
        qu.offer(root);
        while(!qu.isEmpty()){
            le=qu.size();
            while(le>0){
                tn=qu.poll();
                if(tn.left!=null){
                    qu.offer(tn.left);
                }
                if(tn.right!=null){
                    qu.offer(tn.right);
                }
                TreeNode temp=tn.left;
                tn.left=tn.right;
                tn.right=temp;
                le--;
            }
        }
        return root;
    }
}
class Solution(object):
    def invertTree(self, root):
        if root is None:
            return root
        qu=collections.deque()
        qu.append(root)
        while qu:
            le=len(qu)
            while le>0:
                tn=qu.popleft()
                if tn.left:
                    qu.append(tn.left)
                if tn.right:
                    qu.append(tn.right)
                tn.left,tn.right=tn.right,tn.left
                le-=1
        return root

写于皇清宣统辛亥后壹佰壹拾叁年拾月陆日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值