175. 翻转二叉树

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)

 

 

posted @ 2020-08-15 17:18  风不再来  阅读(107)  评论(0编辑  收藏  举报