首页 > 代码库 > Leetcode:Symmetric Tree
Leetcode:Symmetric Tree
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.
分析:
1. 递归法。如果一个树是symmetric的,那么它的左右子树是镜像对称的。对于判断两个树是否镜像对称,如果两棵树的根节点值相同,并且树A的左孩子跟树B的右孩子镜像对称且树A的右还在和树B的左还在镜像对称,那么树A和B是镜像对称的。代码如下:
1 class Solution { 2 public: 3 bool isSymmetric(TreeNode *root) { 4 if(root == NULL) return true; 5 return is_mirror(root->left, root->right); 6 } 7 bool is_mirror(TreeNode *l, TreeNode *r){ 8 if(l == NULL || r == NULL) return l == r; 9 if(l->val != r->val) return false;10 return is_mirror(l->left, r->right) && is_mirror(l->right, r->left);11 }12 };
迭代版算法,是利用栈的树迭代遍历算法的变体。主要思想是把对称的两个节点同时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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。