LeetCode101对称二叉树

题目链接

https://leetcode-cn.com/problems/symmetric-tree/

题解

  • 我写的
  • 递归解法
  • 具体方法见代码注释
// Problem: LeetCode 101
// URL: https://leetcode-cn.com/problems/symmetric-tree/
// Tags: Tree Recursion DFS
// Difficulty: Easy

#include <iostream>
using namespace std;

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
};

class Solution{
private:
    // 判断两个树s和t是否互相对称
    // 有3个要求:
    // ①根节点值相等
    // ②s的左子树和t的右子树互相对称
    // ③s的右子树和t的左子树互相对称
    bool isSymmetric(TreeNode* s, TreeNode* t){
        if(s==nullptr && t==nullptr)
            return true;
        if(s==nullptr || t==nullptr)
            return false;
        if(s->val == t->val)
            return isSymmetric(s->left, t->right) && isSymmetric(s->right, t->left);
        return false;
    }
public:
    bool isSymmetric(TreeNode* root) {
        // 如果该树为空,则为对称的
        if(root==nullptr)
            return true;
        // 左子树和右子树对称
        return isSymmetric(root->left, root->right);
    }
};

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


猜你喜欢

转载自www.cnblogs.com/chouxianyu/p/13380383.html
今日推荐