首页 > 代码库 > LeetCode 101 Symmetric Tree (C)
LeetCode 101 Symmetric Tree (C)
题目:
101. Symmetric Tree
My Submissions
- Total Accepted: 135232
- Total Submissions: 375037
- Difficulty: Easy
- Contributors: Admin
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
Note:
Bonus points if you could solve it both recursively and iteratively.
提示:
Tree Depth-first Search Breadth-first Search
方法1:(效率低,自己写的)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool compare(struct TreeNode* lnode, struct TreeNode* rnode){ if(lnode->val==rnode->val){ if(lnode->left!=NULL && rnode->right!=NULL && lnode->right!=NULL && rnode->left!=NULL){ return compare(lnode->left, rnode->right) && compare(lnode->right, rnode->left); } else if(lnode->left!=NULL && rnode->right!=NULL && lnode->right==NULL && rnode->left==NULL){ return compare(lnode->left, rnode->right); } else if(lnode->left==NULL && rnode->right==NULL && lnode->right!=NULL && rnode->left!=NULL){ return compare(lnode->right, rnode->left); } else if(lnode->left==NULL && rnode->right==NULL && lnode->right==NULL && rnode->left==NULL){ return true; } else return false; } else return false; } bool isSymmetric(struct TreeNode* root) { if(root==NULL){ return true; } else if(root->left==NULL && root->right==NULL){ return true; } else if(root->left!=NULL && root->right!=NULL){ return compare(root->left, root->right); } else return false; }
LeetCode 101 Symmetric Tree (C)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。