美文网首页
[算法][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;
}

总结

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

相关文章

  • 02-13:leetcode重刷2之链表反转

    1、链表反转 2、反转二叉树 3、合并二叉树 4、对称二叉树 1、反转链表 classSolution: defr...

  • 二叉树

    title: 二叉树date: 2016-08-16 14:47:21tags: 算法 二叉树 二叉树的反转

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

    前言 继续继续算法第二篇 题目 简单描述: 反转二叉树 问题详情Invert Binary Tree. 解法: 1...

  • 一些简单的面试经典算法题目

    1. 反转二叉树 解:运用递归;反转左子树,反转右子树,交换左右子树 2.反转单链表 解: 递归解法:Javapu...

  • 算法总结

    基本排序算法 二叉树三种遍历方式 反转链表 反转链表的m到n个节点 股票买入卖出最大利润 全排列 去重的全排列 L...

  • Swift-反转二叉树

    题目: 反转二叉树其实就是二叉树的镜像.4/ 2 7/ \ / 1 3 6 9to4/ ...

  • Golang反转二叉树

    反转二叉树

  • 11 算法

    LRU 算法 反转二叉树 声明节点属性 实现代码: 头插入发 1.假设两个数组为A和B2.A和B都是从小到大的顺序...

  • 翻转二叉树(Java)

    翻转二叉树 对于此题而言,我们使用深度优先算法来遍历二叉树。 1、深度优先算法是根据二叉树的路径进行遍历2、广度优...

  • 二叉树遍历(递归算法和非递归算法)

    实验三 二叉树遍历(递归算法和非递归算法) 一.实验目的 1.掌握二叉树的存储结构与基本操作 2.掌握二叉树的遍历...

网友评论

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

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