翻转二叉树python(leetcode226)
2022/1/15 20:08:03
本文主要是介绍翻转二叉树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)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型