[LeetCode] Symmetric Tree
来源:互联网 发布:linux 设置语言为英文 编辑:程序博客网 时间:2024/06/10 04:20
前言
一道树相关的简单题,判断二叉树是否对称。
题目
https://leetcode.com/problems/symmetric-tree/
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
分析
这类题一般都有递归和非递归两种基本思路。对于此题而言,递归方式相对easy to understand, 而非递归解法需要队列来操作。具体思路可见代码,所有思路的关键就是“镜面对称”。
代码
Recursive solution:
class Solution {public: bool isSymmetric(TreeNode* root) { if (root == NULL) // The tree is empty return 1; return IsMirror(root->left, root->right); // A helper to judge whether two subtree is mirror } bool IsMirror(TreeNode *p, TreeNode *q) { if (p == NULL && q == NULL) return 1; // p and q are both empty tree else if (p == NULL || q == NULL) return 0; // p (or q) is empty return (p->val == q->val) && IsMirror(p->left, q->right) && IsMirror(p->right, q->left); }};
Non-recursive solution:
class Solution {public: bool isSymmetric(TreeNode *root) { TreeNode *left, *right; if (root == NULL) return true; queue<TreeNode*> q1, q2; q1.push(root->left); q2.push(root->right); while (!q1.empty() && !q2.empty()){ left = q1.front(); q1.pop(); right = q2.front(); q2.pop(); if (NULL == left && NULL == right) continue; if (NULL == left || NULL == right) return false; if (left->val != right->val) return false; q1.push(left->left); q1.push(left->right); q2.push(right->right); q2.push(right->left); } return true; }};
0 0
- Leetcode - Tree - Symmetric Tree
- Leetcode - Tree - Symmetric Tree
- LeetCode[Tree]: Symmetric Tree
- [leetcode][tree] Symmetric Tree
- LeetCode: Symmetric Tree
- [Leetcode] Symmetric Tree
- LeetCode : Symmetric Tree
- leetcode 13:symmetric tree
- [LeetCode] Symmetric Tree - Recursively
- [LeetCode] Symmetric Tree - Iteratively
- [LeetCode] Symmetric Tree
- [LeetCode]Symmetric Tree
- Leetcode:Symmetric Tree
- [Leetcode]Symmetric Tree
- Leetcode: Symmetric Tree
- [leetcode]Symmetric Tree
- LeetCode-Symmetric Tree
- [leetcode] Symmetric Tree
- 勿在头文件中定义static变量
- 信号函数
- N个非常有用的Android程序片段(持续更新)
- 具有选择功能的对话框(下拉列表对话框)
- 排序算法总结(归并排序、快速排序)(python实现)
- [LeetCode] Symmetric Tree
- iOS使用MD5加密
- Unrecognized Windows Sockets error: 0: JVM_Bind 异常解决办法
- Python学习笔记-HeadFirstPython 1
- 应用程序无法正常启动(oxc000007b):解决方案
- Learn Some Framework-4 Binder And ServerManager
- 笔记:We don’t need no bounding-boxes: Training object class detectors using only human verification
- 算法代码实现之三向切分快速排序,C/C++实现
- Activity介绍