判断对称二叉树

判断对称二叉树

问题描述

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 `[1,2,2,3,4,4,3]` 是对称的

    1
   / \
  2   2
 / \ / \
3  4 4  3
但是下面这个 `[1,2,2,null,3,null,3]` 则不是镜像对称的
    1
   / \
  2   2
   \   \
   3    3

分析

涉及到树的问题,我们都先考虑递归

  • 一旦一棵树是对称的,那么该树左分支的左结点会等于右分支的右节点…依次类推,左右相对应
  • 我们在递归方法体中设计好比较的逻辑
  • 再提供一个递归出口(到达叶子结点)
  • 设计好参数,一定要是左右对应的

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
   
    public boolean isSymmetric(TreeNode root) {
   
        if(root==null) return true ; 
       return isSymetric(root.left,root.right) ;
    }

        public static boolean isSymetric(TreeNode rootl, TreeNode rootr){
   

        if (rootl==null&&rootr==null) return true ; //遍历到最后->出口
        if (rootl==null||rootr==null) return  false ; 
        if (rootl.val!=rootr.val) return  false ;
        return  (isSymetric(rootl.left,rootr.right)&&isSymetric(rootl.right,rootr.left)) ;
    }
}

性能分析

  • 时间复杂度:O(n)O(n),因为我们遍历整个输入树一次,所以总的运行时间为 O(n)O(n),其中 nn 是树中结点的总数。
  • 空间复杂度:递归调用的次数受树的高度限制。在最糟糕情况下,树是线性的,其高度为 O(n)O(n)。因此,在最糟糕的情况下,由栈上的递归调用造成的空间复杂度为 O(n)O(n)

==========update by 2020 4/16 ==================

C++可运行源代码

#include "string.h"
#include "stdio.h"    
#include "stdlib.h"   
#include "io.h"  
#include "math.h"  
#include "time.h"

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

#define MAXSIZE 100 /* 存储空间初始分配量 */

typedef int Status;		/* Status是函数的类型,其值是函数结果状态代码,如OK等 */

						/* 用于构造二叉树********************************** */
int index = 1;
int index1 = 1;
typedef char String[100]; /*  0号单元存放串的长度 */
String str , str1;

/*分配字符串*/
Status StrAssign(String T, char *chars)
{
   
	int i
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值