LeetCode - Symmetric Tree
2015-01-19 15:55
330 查看
递归方法:
循环方法:
</pre><p></p><pre name="code" class="cpp">/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSymmetricCore(TreeNode *pNode1, TreeNode *pNode2) { if(pNode1 == NULL && pNode2 == NULL) return true; if(pNode1 == NULL || pNode2 == NULL) return false; if(pNode1->val != pNode2->val) return false; else if(!isSymmetricCore(pNode1->left, pNode2->right)) return false; else return isSymmetricCore(pNode1->right, pNode2->left); } bool isSymmetric(TreeNode *root) { bool isSymmetric = true; if(root != NULL) { isSymmetric = isSymmetricCore(root->left, root->right); } return isSymmetric; } };
循环方法:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include<queue> using namespace std; typedef pair<TreeNode*,TreeNode*> nodepair; class Solution { public: bool isSymmetric(TreeNode *root) { // Level-order BFS. queue<nodepair> q; if(root) q.push(make_pair(root->left,root->right)); while(q.size()){ nodepair p=q.front(); q.pop(); if(p.first){ if(!p.second)return false; if(p.first->val != p.second->val) return false; // the order of children pushed to q is the key to the solution. q.push(make_pair(p.first->left,p.second->right)); q.push(make_pair(p.first->right,p.second->left)); } else if(p.second) return false; } return true; } };
相关文章推荐
- LeetCode | Symmetric Tree(镜像树)
- LeetCode101 Symmetric Tree
- 【Leetcode】Symmetric Tree (Tree Judge)
- Symmetric Tree——LeetCode
- 【leetcode c++】101 Symmetric Tree
- leetcode - symmetric tree
- leetcode 之 Symmetric Tree
- leetcode(24).101. Symmetric Tree
- Symmetric Tree —— Leetcode
- LeetCode:Symmetric Tree
- LeetCode[Tree]: Symmetric Tree
- leetcode: Symmetric Tree
- 【LeetCode】101 - Symmetric Tree
- [leetcode] Symmetric Tree
- LeetCode 101. Symmetric Tree(Python)
- Leetcode: Symmetric Tree
- leetcode - Symmetric Tree
- LeetCode Symmetric Tree
- leetcode- Symmetric Tree
- [leetcode]_Symmetric Tree