[LeetCode] Symmetric Tree
LeetCode Tree
2023-09-11 14:17:25 时间
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Note:子树不需要对称,只需要根书的左右是镜像即可。
1 递归,判断leftNode->left和rightNode->right,leftNode->right和rightNode->left,left->val == right->val
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSymmetric(TreeNode *root) { 13 if(root == NULL) return true; 14 return isSymmetricTree(root->left, root->right); 15 } 16 17 bool isSymmetricTree(TreeNode *left, TreeNode *right) 18 { 19 if(left == NULL && right == NULL) return true; //终止条件 20 if(left == NULL || right == NULL) return false; 21 if(left->val == right->val && //合并 22 isSymmetricTree(left->left, right->right) && 23 isSymmetricTree(right->left, left->right) 24 ) 25 return true; 26 27 return false; 28 } 29 30 };
相关文章
- Leetcode 之Balanced Binary Tree(49)
- Java实现 LeetCode 773 滑动谜题(BFS)
- Java实现 LeetCode 685 冗余连接 II(并查集+有向图)
- Java实现 LeetCode 434 字符串中的单词数
- Java实现 LeetCode 146 LRU缓存机制
- Java实现 LeetCode 110 平衡二叉树
- Java实现 LeetCode 44 通配符匹配
- Java实现LeetCode 110. Balanced Binary Tree
- Java实现LeetCode 110. Balanced Binary Tree
- Java实现LeetCode 111. Minimum Depth of Binary Tree
- 【LeetCode算法-28/35】Implement strStr()/Search Insert Position
- ( “树” 之 DFS) 617. 合并二叉树 ——【Leetcode每日一题】
- Python 刷Leetcode题库,顺带学英语单词(43)
- 【LeetCode 85】最大矩形
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- Leetcode 693. 交替位二进制数(结束)
- Leetcode 1346. 检查整数及其两倍数是否存在
- leetcode 70. 爬楼梯 js实现
- leetcode第一刷_Validate Binary Search Tree
- [LeetCode] Flatten Binary Tree to Linked List
- 【LeetCode】461. 汉明距离