zoukankan      html  css  js  c++  java
  • 101. Symmetric Tree. 递归判断镜像二叉树

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    But the following [1,2,2,null,3,null,3] is not:

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/symmetric-tree

    1.思路
    递归求解
    求一棵树是否为镜像叔 转化为 求两棵树是否镜像
    对两棵树而言,考虑三种情况
    (1)两颗都为空,则为镜像
    (2)两颗树中有一个为空且另一个非空,则不为镜像
    (3)若两颗树都不为空,则考虑 若树1左子树=树2右子树 且 树1右子树=树2左子树 ,则为镜像。

    class Solution {
    public:
    
        bool check(TreeNode* q,TreeNode* p){
            if ( !q && !p) return true;
            if ( !q || !p) return false;
    
            return p->val == q->val && check(q->left,p->right) && check(q->right,p->left);
        }
        bool isSymmetric(TreeNode* root) {
    
            return check( root, root);
        }
    };
    
  • 相关阅读:
    while循环学习之统计流量
    MySQL的启动脚本
    UVA 725 Division
    UVA 712 S-tree
    UVA 514
    字典树
    UVA 1595 multimap 的应用
    C++ map 和 multimap
    浮点数
    UVA 227
  • 原文地址:https://www.cnblogs.com/xgbt/p/13019868.html
Copyright © 2011-2022 走看看