首页 > 学院 > 开发设计 > 正文

leetcode 101. Symmetric Tree

2019-11-08 02:57:13
字体:
来源:转载
供稿:网友

题目链接: https://leetcode.com/PRoblems/symmetric-tree/?tab=Description

题目描述:

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:

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

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

    1   / /  2   2   /   /   3    3

分别按照先左后右和先右后左的顺序进行DFS,比较对应节点的值是否相等

代码:

/** * 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||(root->left==NULL&&root->right==NULL))            return 1;        else return DFS(root->left,root->right);    }    bool DFS(TreeNode* root1,TreeNode* root2)    {        if(root1==NULL&&root2==NULL)            return 1;        else if((root1==NULL&&root2!=NULL)||(root1!=NULL&&root2==NULL))            return 0;        else if(root1->val!=root2->val)            return 0;        else            return DFS(root1->left,root2->right)&&DFS(root1->right,root2->left);    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表