您的位置:首页 > 编程语言 > C语言/C++

Leetcode 101. Symmetric Tree( C++版)

2017-04-09 16:42 519 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree 
[1,2,2,3,4,4,3]
 is symmetric:
1
/ \
2   2
/ \ / \
3  4 4  3


But the following 
[1,2,2,null,3,null,3]
 is not:

1
/ \
2   2
\   \
3    3


Note:

Bonus points if you could solve it both recursively and iteratively.

思路分析:

对称二叉树需要满足:

根的左孩子和右孩子结点值相等

根的左子树和右子树对称(也就是左子树的左孩子的结点值 == 右子树的右孩子的结点值 && 左子树的右孩子的结点值 == 右子树的左孩子的结点值)

代码:

方法一递归:

/**
* Definition for a binary tree node.
* 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) return true;//****不要忘记判断root是否为空

return isSymNode(root -> left, r -> right);//判断根的左右子树是否对称
}
bool isSymNode(TreeNode* l, TreeNode* r){
if(!l && !r) return true;//左右子树都为空
if(!l || !r) return false;//左右子树有一个为空
if(l -> val == r -> val){//左右子树均不为空,判断左子树和右子树是否均为对称
return isSymNode(l -> left, r -> right) && isSymNode(l -> right, r -> left);
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Symmetric Tree