码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-07-15 23:31:48      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:als   ror   root   temp   ini   load   for   img   info   

技术图片

 

 

/**
 * 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;


    }
    
}

 

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

标签:als   ror   root   temp   ini   load   for   img   info   

原文地址:https://www.cnblogs.com/lyr-2000/p/13307041.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!