美文网首页
226. 翻转二叉树 各种解法

226. 翻转二叉树 各种解法

作者: 如沙雨下 | 来源:发表于2019-01-05 10:50 被阅读13次

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

谷歌:我们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

相关文章

网友评论

      本文标题:226. 翻转二叉树 各种解法

      本文链接:https://www.haomeiwen.com/subject/jvkrrqtx.html