资讯专栏INFORMATION COLUMN

[LintCode] Invert Binary Tree

Loong_T / 760人阅读

Example
  1         1
 /        / 
2   3  => 3   2
   /       
  4         4
  
Solution

Recursion:

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

Queue/linkedlist:

用queue的方法要熟练掌握。

public class Solution {
    public void invertBinaryTree(TreeNode root) {
        if (root == null) return;
        Queue queue = new LinkedList();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65508.html

相关文章

  • [Leetcode] Invert Binary Tree 翻转二叉树

    摘要:原题链接递归法复杂度时间空间递归栈空间思路这个难倒大神的题也是非常经典的一道测试对二叉树遍历理解的题。递归的终止条件是当遇到空节点或叶子节点时,不再交换,直接返回该节点。代码给出的是后序遍历的自下而上的交换,先序遍历的话就是自上而下的交换。 Invert Binary Tree Invert a binary tree. 4 / 2 7 / ...

    leone 评论0 收藏0
  • [LeetCode] 226. Invert Binary Tree

    Problem Invert a binary tree. Example: Input: 4 / 2 7 / / 1 3 6 9 Output: 4 / 7 2 / / 9 6 3 1 Trivia:This problem was inspired by this original t...

    xiaodao 评论0 收藏0
  • Leetcode PHP题解--D59 226. Invert Binary Tree

    摘要:题目链接题目分析反转二叉树。思路类似反转两个变量,先把左右子树存进单独的变量,再相互覆盖左右子树。并对子树进行相同的操作。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D59 226. Invert Binary Tree 题目链接 226. Invert Binary Tree 题目分析 反转二叉树。 思路 类似反转两个变量,先把左右子树存进单独的变量,再相互覆盖左右子树。 并...

    miqt 评论0 收藏0
  • 226. Invert Binary Tree

    摘要:题目链接思路如果需要反转一个二叉树,那么我们需要遍历整个树的所有节点。这两种办法分别可以用迭代或者递归的办法实现。算法复杂度递归时间空间时间空间代码递归 题目链接:Invert Binary Tree 思路:如果需要反转一个二叉树,那么我们需要遍历整个树的所有节点。如果想遍历所有的节点,我们可以用Depth First Search(DFS)或者Breadth First Search...

    cppprimer 评论0 收藏0
  • [LintCode] Check Full Binary Tree

    Description A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More in...

    Keven 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<