226. 翻转二叉树 各种解法

题目描述:
翻转一棵二叉树。

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

一.JAVA迭代

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.empty()) {
            TreeNode node = stack.pop();
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        return root;
    }
}

二.JAVA递归

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return null;
        }
        root.left=invertTree(root.left);
        root.right=invertTree(root.right);
        TreeNode temp =root.left;
        root.left=root.right;
        root.right=temp;
        return root;
    }
}

三.Python

class Solution:
    def invertTree(self, root):
        if root :
            root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)
        return root
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目描述翻转一棵二叉树。示例:输入: 4 / \ 2 7 / \ / \1 3 ...
    逍遥ii阅读 2,361评论 0 1
  • 翻转一棵二叉树。 示例: 备注: 这个问题是受到 Max Howell 的 原问题 启发的 :谷歌:我们90%的工...
    闭门造折阅读 1,722评论 0 0
  • 去年二叉树算法的事情闹的沸沸扬扬,起因是Homebrew 的作者 @Max Howell 在 twitter 上发...
    Masazumi柒阅读 5,510评论 0 8
  • HomeBrew作者,天才程序员Max Howell去Google面试),结果却因不会在白板上翻转二叉树被Goog...
    bo_song阅读 4,402评论 0 4
  • 最近珠三角,可谓动荡。每天都有人离职,一派肃杀的气象。冬天已经来临,熬过去!
    L牧阅读 1,657评论 0 0