美文网首页
[算法][2]反转二叉树

[算法][2]反转二叉树

作者: Marlon_IT | 来源:发表于2018-01-19 17:29 被阅读33次

    前言

    继续继续算法第二篇

    题目

    • 简单描述:

    反转二叉树

    问题详情
    Invert Binary Tree.

    解法:

    1. 解法一 递归

        public TreeNode invertTree(TreeNode root) {
            if (root == null) {
                return null;
            }
    
            if (root.left != null) {
                invertTree(root.left);
            }
            if (root.right != null) {
                invertTree(root.right);
            }
    
            TreeNode treeNode = root.left;
            root.left = root.right;
            root.right = treeNode;
    
            return root;
    
        }
    
    

    2. 解法二 非递归(经典解法)

    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode current = queue.poll();
            TreeNode temp = current.left;
            current.left = current.right;
            current.right = temp;
            if (current.left != null) queue.add(current.left);
            if (current.right != null) queue.add(current.right);
        }
        return root;
    }
    
    

    总结

    算法贵在持之以恒,做多了 就懂了!继续干小伙伴们!!!

    相关文章

      网友评论

          本文标题:[算法][2]反转二叉树

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