码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的递归解法

时间:2021-06-25 16:45:06      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:nod   tco   http   翻转   for   区别   val   ini   root   

贴上大佬的博客地址:https://labuladong.gitee.io/algo/2/18/20/

这一部分总得来说比较简单,注意边界值的判断就行了。下面是贴上实际的代码

"""
翻转二叉树
https://leetcode-cn.com/problems/invert-binary-tree/
"""
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        """
        注意判断边界值,
        在子节点递归调用翻转函数        
        """
        if root == None:
            return root
        tmp = root.left 
        root.left = root.right
        root.right = tmp
        self.invertTree(root.left)
        self.invertTree(root.right)

        return root
"""
填充每个节点的下一个右侧节点
https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
"""

# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: ‘Node‘ = None, right: ‘Node‘ = None, next: ‘Node‘ = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next


class Solution:
    """
    注意对比与226 翻转二叉树的区别,这里的递归函数中传入了两个参数(两个节点)
    """
    def connect(self, root: ‘Node‘) -> ‘Node‘:
        if root == None:
            return root

        self.connectTwoNode(root.left, root.right)

        return root
    
    def connectTwoNode(self, left, right):
        # 编辑判断要放在这里做,在connect中做没有用,因为递归调用的是这个函数
        if left == None or right == None:
            return None
        left.next = right
        self.connectTwoNode(left.left, left.right)
        self.connectTwoNode(left.right, right.left)
        self.connectTwoNode(right.left, right.right)
"""
填充每个节点的下一个右侧节点
https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
"""

# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: ‘Node‘ = None, right: ‘Node‘ = None, next: ‘Node‘ = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next


class Solution:
    """
    注意对比与226 翻转二叉树的区别,这里的递归函数中传入了两个参数(两个节点)
    """
    def connect(self, root: ‘Node‘) -> ‘Node‘:
        if root == None:
            return root

        self.connectTwoNode(root.left, root.right)

        return root
    
    def connectTwoNode(self, left, right):
        # 编辑判断要放在这里做,在connect中做没有用,因为递归调用的是这个函数
        if left == None or right == None:
            return None
        left.next = right
        self.connectTwoNode(left.left, left.right)
        self.connectTwoNode(left.right, right.left)
        self.connectTwoNode(right.left, right.right)

二叉树的递归解法

标签:nod   tco   http   翻转   for   区别   val   ini   root   

原文地址:https://www.cnblogs.com/panzhixiang/p/14928756.html

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