Leetcode Invert Binary Tree python 反转二叉树的问题 还是DFS和BFS,递归和迭代的操作

Leetcode 226题 Invert Binary Tree
Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

据说是谷歌面试题。


很简单了,二叉树的题就是使用递归或者迭代,数据结构直接操作或者用栈或队列,思路用DFS或者BFS。
不懂什么是DFS和BFS的可以看我的这篇文章。
Leetcode Symmetric Tree Python 学习递归/DFS/BFS

直接上代码:
DFS递归:
很简单,就是二叉树不存在的时候返回根节点,存在的时候是一个简单的交换。

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

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return root
        temp = root.left
        root.left = self.invertTree(root.right)
        root.right = self.invertTree(temp)
        return root

python简单的语言再优化一下,不过还是python得传统特色效率很低。

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root:
            root.right, root.left = self.invertTree(root.left),self.invertTree(root.right)
        return root

BFS 用栈操作。把递归改迭代就是添加一个栈套用模板。

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return root
        
        stack = []
        stack.append(root)
        while stack:
            node = stack.pop()
            if not node:
                continue
            node.right,node.left = node.left,node.right
            stack.append(node.right)
            stack.append(node.left)
        
        return root

2020/03/30
疫情中的英国,
加油!

发布了20 篇原创文章 · 获赞 1 · 访问量 792

猜你喜欢

转载自blog.csdn.net/weixin_43860294/article/details/105211908
今日推荐