前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 226. 翻转二叉树

LeetCode 226. 翻转二叉树

作者头像
freesan44
发布2020-03-20 10:06:12
2940
发布2020-03-20 10:06:12
举报
文章被收录于专栏:freesan44freesan44

题目

翻转一棵二叉树。

代码语言:javascript
复制
示例:

输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
输出:

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

备注: 这个问题是受到 Max Howell 的 原问题 启发的 :

谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。

解题思路

广度优先搜索,深度优先搜索

代码语言:javascript
复制
# 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 root:
        #     temp = root.left
        #     root.left = root.right
        #     root.right = temp
        #     root.left = self.invertTree(root.left)
        #     root.right = self.invertTree(root.right)
        #     return root;
        # else:
        #     return None
        ##广度优先,用堆栈来处理
        if root:
            stack = [root]
            while stack:
                node = stack.pop()
                node.left, node.right = node.right, node.left
                if node.left:
                    stack.append(node.left)
                if node.right:
                    stack.append(node.right)
        else:
            return None

Github:https://github.com/freesan44/LeetCode

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档