Python教程

翻转二叉树python(leetcode226)

本文主要是介绍翻转二叉树python(leetcode226),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

226. 翻转二叉树 

不同的二叉树搜索方法不同的做法

1 深度优先搜索

迭代和递归

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        # 深度优先搜索 用stack 前序遍历
        if not root:
            return root
        stack = [root]

        # 中左右
        while stack:
            cur  = stack.pop()
            cur.left, cur.right = cur.right, cur.left
            if cur.right:
                stack.append(cur.right)
            if cur.left:
                stack.append(cur.left)
        return root

# class Solution(object):
#     def invertTree(self, root):
          # 递归
          #递归的中序遍历是不行的
#         if not root:
#             return 
#         root.left, root.right = root.right, root.left
#         self.invertTree(root.left)
#         self.invertTree(root.right)
#         return root

2广度优先搜索

层序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from collections import deque
class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        # 使用层序遍历 用deque
        if not root:
            return root
        que = deque([root])
        while que:
            for _ in range(len(que)):
                cur = que.popleft()
                cur.left, cur.right = cur.right, cur.left
                if cur.left:
                    que.append(cur.left)
                if cur.right:
                    que.append(cur.right)
        return root

这篇关于翻转二叉树python(leetcode226)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!