【C++】【LeetCode】101. Symmetric Tree

来源:互联网 发布:fifo算法c语言实现 编辑:程序博客网 时间:2024/06/01 23:10

题目

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。

思路

这道题可以通过递归判断两个节点是否是对称的。

代码

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool isSymmetric(TreeNode* root) {        if (root == NULL) {            return true;        }        return isSymmetric(root->left, root->right);    }    bool isSymmetric(TreeNode* lNode, TreeNode* rNode) {        if (lNode == NULL && rNode == NULL) {            return true;        } else if (lNode == NULL || rNode == NULL || (lNode->val != rNode->val)) {            return false;        }        return isSymmetric(lNode->left, rNode->right) && isSymmetric(lNode->right, rNode->left);    }};
原创粉丝点击