码迷,mamicode.com
首页 > 编程语言 > 详细

算法 翻转二叉树 dfs

时间:2019-09-29 22:09:26      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:左右   amp   代码   hal   desc   body   @param   red   def   

翻转二叉树

翻转一棵二叉树。左右子树交换。

Example

样例 1:

输入: {1,3,#}
输出: {1,#,3}
解释:
	  1    1
	 /  =>  	3        3

样例 2:

输入: {1,2,3,#,#,4}
输出: {1,3,2,#,4}
解释: 
	
      1         1
     / \       /     2   3  => 3   2
       /             4         4

Challenge

递归固然可行,能否写个非递归的?

代码:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: a TreeNode, the root of the binary tree
    @return: nothing
    """
    def invertBinaryTree(self, root):
        # write your code here
        if not root:
            return
        self.invertBinaryTree(root.left)
        self.invertBinaryTree(root.right)
        root.left, root.right = root.right, root.left
          

当然,使用先序遍历也可以

 

算法 翻转二叉树 dfs

标签:左右   amp   代码   hal   desc   body   @param   red   def   

原文地址:https://www.cnblogs.com/bonelee/p/11609991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!