Leetcode:Symmetric Tree
2015-01-02 20:57
309 查看
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.
分析:
1. 递归法。如果一个树是symmetric的,那么它的左右子树是镜像对称的。对于判断两个树是否镜像对称,如果两棵树的根节点值相同,并且树A的左孩子跟树B的右孩子镜像对称且树A的右还在和树B的左还在镜像对称,那么树A和B是镜像对称的。代码如下:
迭代版算法,是利用栈的树迭代遍历算法的变体。主要思想是把对称的两个节点同时Push到栈里,然后每次从栈顶pop两个节点判断是否相同。代码如下:
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.
分析:
1. 递归法。如果一个树是symmetric的,那么它的左右子树是镜像对称的。对于判断两个树是否镜像对称,如果两棵树的根节点值相同,并且树A的左孩子跟树B的右孩子镜像对称且树A的右还在和树B的左还在镜像对称,那么树A和B是镜像对称的。代码如下:
class Solution { public: bool isSymmetric(TreeNode *root) { if(root == NULL) return true; return is_mirror(root->left, root->right); } bool is_mirror(TreeNode *l, TreeNode *r){ if(l == NULL || r == NULL) return l == r; if(l->val != r->val) return false; return is_mirror(l->left, r->right) && is_mirror(l->right, r->left); } };
迭代版算法,是利用栈的树迭代遍历算法的变体。主要思想是把对称的两个节点同时Push到栈里,然后每次从栈顶pop两个节点判断是否相同。代码如下:
class Solution { public: bool isSymmetric(TreeNode *root) { if(root == NULL) return true; stack<TreeNode *> s; s.push(root->left); s.push(root->right); while(!s.empty()){ TreeNode *r = s.top();s.pop(); TreeNode *l = s.top();s.pop(); if(r == NULL && l == NULL) continue;//this is very import if(r == NULL || l == NULL) return false; if(r->val != l->val) return false; s.push(r->left); s.push(l->right); s.push(r->right); s.push(l->left); } 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