重做_二叉树的镜像

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);
            }
            
            
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容