美文网首页
【1错1对0】二叉树的镜像

【1错1对0】二叉树的镜像

作者: 7ccc099f4608 | 来源:发表于2019-01-27 15:20 被阅读5次

https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
| 日期 | 是否一次通过 | comment |
|----|----|----|
|2019-01-26 13:20|N|实质是preOrder + swap|
|2019-01-27 13:20|Y||

题目:操作给定的二叉树,将其变换为源二叉树的镜像。

image.png

图片来源:https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

1. 递归

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

2.非递归

import java.util.*;
public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null) {
            return;
        }
        
        Stack<TreeNode> nodeS = new Stack<>();
        nodeS.push(root);
        
        while(!nodeS.isEmpty()) {
            TreeNode node = nodeS.pop();
            TreeNode tempNode = node.left;
            node.left = node.right;
            node.right = tempNode;
            
            if(node.left != null) {
                nodeS.push(node.left);
            }
            
            if(node.right != null) {
                nodeS.push(node.right);
            }
            
            
        }
    }
}

相关文章

  • 【1错1对0】二叉树的镜像

    https://www.nowcoder.com/practice/564f4c26aa584921bc75623...

  • 剑指offer(java版)——解决面试题的思路

    1.镜像二叉树 题目描述操作给定的二叉树,将其变换为源二叉树的镜像。输入描述:二叉树的镜像定义:源二叉树8/ \...

  • 《剑指offer》— JavaScript(18)二叉树的镜像

    二叉树的镜像 题目描述 操作给定的二叉树,将其变换为源二叉树的镜像。 相关知识 二叉树的镜像定义:源二叉树 镜像二...

  • 剑指offer小结第二波

    二叉树专题系列 1. 镜像类 题目描述: 操作给定的二叉树,将其变换为源二叉树的镜像。 Ying的解法: 二叉树的...

  • JZ-018-二叉树的镜像

    二叉树的镜像 题目描述 操作给定的二叉树,将其变换为源二叉树的镜像。题目链接: 二叉树的镜像[https://ww...

  • 二叉树的镜像-java

    二叉树的镜像 题目描述 操作给定的二叉树,将其变换为源二叉树的镜像。输入描述:二叉树的镜像定义:源二叉树8/ 6...

  • 剑指offer-18~20

    18.二叉树的镜像操作给定的二叉树,将其变换为源二叉树的镜像。输入描述:二叉树的镜像定义:源二叉树8/ 6 10/...

  • 二叉树的镜像

    题目描述 操作给定的二叉树,将其变换为源二叉树的镜像。 输入描述 二叉树的镜像定义:源二叉树与镜像二叉树 代码 总...

  • 数据结构之——翻转二叉树

    介绍:翻转二叉树,又叫求二叉树的镜像,就是把二叉树的左右子树对调(当然是递归的) 思路: 0.创建类 Binary...

  • 二叉树镜像(反转二叉树)

    二叉树的镜像 题目描述 操作给定的二叉树,将其变换为源二叉树的镜像。 相关知识 二叉树的镜像定义: 思路 有关二叉...

网友评论

      本文标题:【1错1对0】二叉树的镜像

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