zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    第十周(11.18-11.24)----结对编程----感悟
    第十周(11.18-11.24)----分数计算----(2)对两个分数进行加减乘除
    第十周(11.18-11.24)----规格说明书练习----吉林市1日游
    浪潮之巅读后感
    闽江学院软件学院2015级学生职业人物访谈
    第五作业
    第4周~第12周周记
    兴趣问题清单
    学习进度
    价值观作业
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13509465.html
Copyright © 2011-2022 走看看