您的位置:首页 > 其它

Symmetric Tree(easy)

2016-05-26 18:06 155 查看
题目】 

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.

confused what 
"{1,#,2,3}"
 means? >
read more on how binary tree is serialized on OJ.

题意

      判断一棵树是否对称

分析

      递归,保存左右两个节点,然后判断leftNode->left和rightNode->right,以及leftNode->right和rightNode->left,如此不断递归如果对称.还有中序遍历的结果一定也是对称的。

实现

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
if (root.left == null && root.right == null) return true;
return isMiror(root.left, root.right);

}

public boolean isMiror(TreeNode n1, TreeNode n2) {
if (n1 == null && n2 == null) return true;
if (n1 == null && n2 != null) return false;
if (n1 != null && n2 == null) return false;
if (n1.val != n2.val) return false;
return isMiror(n1.left, n2.right) && isMiror(n1.right, n2.left);
}
}

public boolean isSymmetric(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null) return true;

ArrayList<Integer> ret = new ArrayList<Integer>();
inorder(root, ret);
for(int i=0, j=ret.size()-1; i<j; i++, j--){
if(ret.get(i) != ret.get(j))
return false;
}
return true;
}

public void inorder(TreeNode root, ArrayList<Integer> ret){
if(root == null) return;
if(root.left!=null)
inorder(root.left, ret);
ret.add(root.val);
if(root.right!=null)
inorder(root.right, ret);
}

非递归:

bool isSymmetric(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root==NULL)return true;
queue<TreeNode*> lt,rt;
if(root->left) lt.push(root->left);
if(root->right) rt.push(root->right);
TreeNode* l;
TreeNode* r;
while(!lt.empty() && !rt.empty())
{
l = lt.front();lt.pop();
r = rt.front();rt.pop();
if(l == NULL && r == NULL) continue;
if(l == NULL || r == NULL) return false;
if(l->val != r->val) return false;
lt.push(l->left);
lt.push(l->right);
rt.push(r->right);
rt.push(r->left);
}
if(lt.empty() && rt.empty())
return true;
else
return false;
}
class Solution {
public:
bool isSymmetric (TreeNode* root) {
if (!root) return true;
stack<TreeNode*> s;
s.push(root->left);
s.push(root->right);
while (!s.empty ()) {
auto p = s.top (); s.pop();
auto q = s.top (); s.pop();
if (!p && !q) continue;
if (!p || !q) return false;
if (p->val != q->val) return false;
s.push(p->left);
s.push(q->right);
s.push(p->right);
s.push(q->left);
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: