leetcode: Symmetric Tree
2014-07-02 20:21
274 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
递归
非递归:
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.
递归
/** * 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 isSymmetric(TreeNode *root) { if( root == NULL) return true; return core( root->left, root->right); } bool core( TreeNode *root_left, TreeNode *root_right){ if( !root_left && !root_right) return true; if( !root_left || !root_right) return false; return root_left->val == root_right->val && core( root_left->left, root_right->right) && core( root_left->right, root_right->left); } };
非递归:
/** * 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 isSymmetric(TreeNode *root) { if( root == NULL) return true; stack< TreeNode *> stk; stk.push(root->left); stk.push(root->right); while( !stk.empty()){ auto p = stk.top(); stk.pop(); auto q = stk.top(); stk.pop(); if( !q && !p) continue; if( !q || !p) return false; if( p->val == q->val){ stk.push(p->left); stk.push(q->right); stk.push(p->right); stk.push(q->left); } else return false; } return true; } };
相关文章推荐
- 【LeetCode】Symmetric Tree 判断一棵树是否是镜像的
- LeetCode 101. Symmetric Tree
- Leetcode 笔记 101 - Symmetric Tree
- Leetcode - Tree - Symmetric Tree
- LeetCode——Symmetric Tree
- [leetcode] 101. Symmetric Tree
- leetcode-Symmetric Tree 对称树
- 和大神们学习每天一题(leetcode)-Symmetric Tree
- [Leetcode]Symmetric Tree
- [LeetCode]Symmetric Tree
- leetcode--Symmetric Tree
- leetcode_Symmetric Tree_判断二叉树镜像对称_easy_方法
- [LeetCode] Symmetric Tree 判断二叉树是否为对称二叉树
- leetcode-Symmetric Tree
- leetcode-Symmetric Tree
- LeetCode-Symmetric Tree
- Leetcode#101. Symmetric Tree(对称树)
- Leetcode | Symmetric Tree
- LeetCode 101 Symmetric Tree
- LeetCode101. Symmetric Tree