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
我的解法如下:
一个二叉树的对称实际就是它的左子树和右子树两者互相对称(注意不是它的左树和右树各自分别对称)。那么把一棵树的对称转化为两棵树的对称问题。而树A和树B对称是可以运用递归来定义的:
树A和树B对称 == 树A的根节点等于树B的根节点 && 树A的左子树和树B的右子树对称 && 树A的右子树和树B的左子树对称
我的代码如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool AreSymmetric(TreeNode* first, TreeNode* second) {
if((first == NULL) && (second == NULL))
return true;
else if((first) && (second == NULL))
return false;
else if((first == NULL) && (second))
return false;
if(first->val != second->val)
return false;
else{
return (AreSymmetric(first->left, second->right) && AreSymmetric(first->right, second->left));
}
}
bool isSymmetric(TreeNode *root) {
if(!root) return true;
return AreSymmetric(root->left, root->right);
}
};
引申:
二叉树的遍历问题。二叉树只需要每个节点存两个子节点的信息,而不用存父节点的信息,就可以完成每个遍历,方法就是用递归。实际上用递归就是用函数栈代替了父节点的作用。函数的调用顺序就完成了对每个节点的父节点的记忆。
一个递归遍历二叉树的例子如下:
对一个二叉树,遍历它的方法是:
1.遍历左子树
2.遍历右子树
3.直到叶子节点(没有左子树和右子树),对节点做动作。
代码如下:
Class BTree {
int val;
BTree* left, *right;
public:
void VisitBTree(BTree* TreeNode){
if ((!TreeNode->left) && (!TreeNode->right)) { //叶子节点
DoSomething(TreeNode->val);
return;
}
if (TreeNode->left)
VisitBTree(TreeNode->left);
if (TreeNode->right)
VisitBTree(TreeNode->right);
return;
}
}