【一次过】Lintcode 1360. 对称树

本文介绍了一种检查二叉树是否为自身镜像的方法,通过对左子树进行反转,然后比较反转后的左子树与右子树是否相同来判断。提供了递归实现方式,包括反转树和比较树是否相同的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定二叉树,检查它是否是自身的镜像(即,围绕其中心对称)。

样例

例如,这个二叉树“{1,2,2,3,4,4,3}”是对称的:

    1
   / \
  2   2
 / \ / \
3  4 4  3

的英文然如下  {1,2,2,#,3,#,3} 不是:

    1
   / \
  2   2
   \   \
   3    3

注意事项

如果您可以同时用递归和迭代解决它,那么奖励分数。


解题思路:

先对左子树反转,参考:Lintcode 175. 翻转二叉树,然后比较两子树是否相等即可,参考:Lintcode 469. Same Tree

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: root of the given tree
     * @return: whether it is a mirror of itself 
     */
    public boolean isSymmetric(TreeNode root) {
        // Write your code here
        if(root == null)
            return true;
        
        invertTree(root.left);
        
        return isSame(root.left, root.right);
    }
    
    private void invertTree(TreeNode root){
        if(root == null)
            return;
            
        invertTree(root.left);
        invertTree(root.right);
        
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }
    
    private boolean isSame(TreeNode node1, TreeNode node2){
        if(node1 == null && node2 == null)
            return true;
            
        if(node1 == null || node2 == null)
            return false;
        
        if(isSame(node1.left, node2.left) && isSame(node1.right, node2.right))
            return (node1.val == node2.val) ? true : false;
            
        return false;
    }
}

二刷:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: root of the given tree
     * @return: whether it is a mirror of itself 
     */
    public boolean isSymmetric(TreeNode root) {
        // Write your code here
        if(root == null)
            return true;
        
        return isSymmetric(root.left, root.right);
    }
    
    private boolean isSymmetric(TreeNode node1, TreeNode node2){
        if(node1 == null && node2 == null)
            return true;
        if(node1 == null || node2 == null)
            return false;
            
        if(node1.val != node2.val)
            return false;
        
        return isSymmetric(node1.left, node2.right) && isSymmetric(node1.right, node2.left);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值