101.Symmetric Tree
题目描述:
对称树
思路:
递归和非递归两种方法实现,递归要有出口,非递归采用depth-first-search遍历。
1. 递归解法
此解法参考他人。
/**
* 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 judge(TreeNode *lchild, TreeNode *rchild) {
if (lchild == 0 || rchild == 0) {
if (lchild == 0 && rchild == 0)
return true;
else
return false;
}
if (lchild->val != rchild->val)
return false;
return judge(lchild->left, rchild->right) && judge(lchild->right, rchild->left);
}
bool isSymmetric(TreeNode* root) {
if (root == 0)
return true;
bool res;
res = judge(root->left, root->right);
return res;
}
};
2. 非递归解法
非递归解法。
二叉树层次遍历。
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == 0)
return true;
queue<TreeNode *> left;
queue<TreeNode *> right;
left.push(root->left);
right.push(root->right);
while (!left.empty() && !right.empty()) {
TreeNode *node1 = left.front();
TreeNode *node2 = right.front();
left.pop();
right.pop();
if ((node1 && !node2) || (!node1 && node2))
return false;
if (node1 && node2) {
if (node1->val != node2->val)
return false;
left.push(node1->left);
left.push(node1->right);
right.push(node2->right);
right.push(node2->left);
}
}
return true;
}
};