• #树#递归#二叉树的镜像


    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode mirrorTree(TreeNode root) {
            return mirror(root);
        }
        TreeNode mirror(TreeNode root) {
            if(root == null) return root;
            TreeNode temp = root.left;
            root.left =  root.right;
            root.right = temp;
            mirror(root.left);
            mirror(root.right);
            return root;
    
        }
    }
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode mirrorTree(TreeNode root) {
            if(root == null) return root;
            Deque<TreeNode> q = new LinkedList<>();
            q.push(root);
            TreeNode temp = null;
            while(q.isEmpty() == false) {
                TreeNode parent = q.poll();
                temp  = parent.left;
                parent.left = parent.right;
                parent.right = temp;
                if(parent.left!=null) {
                    q.offer(parent.left);
                }
                if(parent.right!=null) {
                    q.offer(parent.right);
                }
            }
            return root;
    
    
        }
        
    }
    
  • 相关阅读:
    面向过程
    生成器
    迭代器
    装饰器
    函数及嵌套
    字符编码与文件操作
    linux_ssh
    LNMP
    BZOJ 3238: [Ahoi2013]差异
    BZOJ 3998: [TJOI2015]弦论
  • 原文地址:https://www.cnblogs.com/lyr-2000/p/13307041.html
Copyright © 2020-2023  润新知