反转二叉树——invert-binary-tree

非递归版本:

 1 """
 2 Definition of TreeNode:
 3 class TreeNode:
 4     def __init__(self, val):
 5         self.val = val
 6         self.left, self.right = None, None
 7 """
 8 
 9 class Solution:
10     """
11     @param root: a TreeNode, the root of the binary tree
12     @return: nothing
13     """
14     def invertBinaryTree(self, root):
15         # write your code here
16         if root == None:
17             return
18         stack = [root]
19         while stack:
20             cur = stack.pop()
21             cur.left, cur.right = cur.right, cur.left
22             if cur.left:
23                 stack.append(cur.left)
24             if cur.right:
25                 stack.append(cur.right)

 

递归版本:

 1 """
 2 Definition of TreeNode:
 3 class TreeNode:
 4     def __init__(self, val):
 5         self.val = val
 6         self.left, self.right = None, None
 7 """
 8 
 9 class Solution:
10     """
11     @param root: a TreeNode, the root of the binary tree
12     @return: nothing
13     """
14     def invertBinaryTree(self, root):
15         # write your code here
16         root = self.helper(root)
17     
18     def helper(self, root):
19         if root is not None:
20             root.left, root.right = self.helper(root.right), self.helper(root.left)
21         return root

 

转载于:https://www.cnblogs.com/liqiniuniu/p/10510831.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值