175. 翻转二叉树

中文English

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

样例

样例 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

挑战

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

 
输入测试数据 (每行一个参数)如何理解测试数据?
 
回溯写法:
得到左右的节点,然后root.left,root.right = left_node, right_node分别指向
"""
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 None
        
        left_node = self.invertBinaryTree(root.left)
        right_node = self.dfinvertBinaryTrees(root.right)
        
        root.right = left_node
        root.left = right_node
        
        return root
        

 

 分治法:

"""
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 
        
        left_node = root.left
        right_node = root.right
        
        root.left = right_node
        root.right = left_node
        
        self.invertBinaryTree(root.left)
        self.invertBinaryTree(root.right)

 

 

相关文章:

  • 2021-07-28
  • 2022-12-23
  • 2021-10-15
  • 2021-06-05
  • 2022-12-23
  • 2022-12-23
  • 2021-10-10
  • 2022-12-23
猜你喜欢
  • 2021-08-25
  • 2021-11-25
  • 2021-10-20
  • 2022-01-13
  • 2021-12-03
  • 2021-09-01
  • 2021-06-14
相关资源
相似解决方案