zoukankan      html  css  js  c++  java
  • 二叉树的镜像

    请完成一个函数,输入一个二叉树,该函数输出它的镜像。

    例如输入:

            4
          /  
       2      7
      /      / 
    1   3  6    9
    镜像输出:

            4
          /   
        7      2
      /       / 
    9   6   3    1

    示例 1:

    输入:root = [4,2,7,1,3,6,9]
    输出:[4,7,2,9,6,3,1]
     

    限制:

    0 <= 节点个数 <= 1000

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof

    /**
     * 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 null;
            return swap(root); 
        }
        private TreeNode swap(TreeNode node){
            if(node==null) return null;
            if( node.left!=null || node.right!=null){
                TreeNode newnode=new TreeNode();
                newnode=node.left;
                node.left=node.right;
                node.right=newnode;
                swap(node.left);
                swap(node.right);
            }
            return node;
    
        }
    }

    解题思路:主要还是使用递归思想;对每一个节点都进行判断;如果有左子树或者右子树就进行节点之间的交换即可。

  • 相关阅读:
    【LeetCode】在排序数组中查找元素的第一个和最后一个位置
    【LeetCode】搜索旋转排序数组
    【LeetCode】组合总和
    【LeetCode】电话号码的字母组合
    【LeetCode】对称二叉树
    【LeetCode】验证二叉搜索树
    【LeetCode】分发糖果
    Go学习笔记
    mybatis
    redis
  • 原文地址:https://www.cnblogs.com/-jiuqi/p/13410405.html
Copyright © 2011-2022 走看看