Q:请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
A:
递归:
bool isSymmetrical(TreeNode *pRoot) {
if (!pRoot)
return true;
return comp(pRoot->left, pRoot->right);
}
bool comp(TreeNode *left, TreeNode *right) {
if (left == nullptr)
return right == nullptr;
if (right == nullptr)
return false;
if(left->val!=right->val)
return false;
return comp(left->left, right->right) && comp(left->right, right->left);
}
非递归(感谢@hustZa):
利用DFS:
出栈的时候也是成对成对的 ,
1.若都为空,继续;
2.一个为空,返回false;
3.不为空,比较当前值,值不等,返回false;
4.确定入栈顺序,每次入栈都是成对成对的,如left.left, right.right ;left.rigth,right.left
boolean isSymmetricalDFS(TreeNode pRoot)
{
if(pRoot == null) return true;
Stack<TreeNode> s = new Stack<>();
s.push(pRoot.left);
s.push(pRoot.right);
while(!s.empty()) {
TreeNode right = s.pop();//成对取出
TreeNode left = s.pop();
if(left == null && right == null) continue;
if(left == null || right == null) return false;
if(left.val != right.val) return false;
//成对插入
s.push(left.left);
s.push(right.right);
s.push(left.right);
s.push(right.left);
}
return true;
}
利用BFS:
出队的时候也是成对成对的
1.若都为空,继续;
2.一个为空,返回false;
3.不为空,比较当前值,值不等,返回false;
4.确定入队顺序,每次入队都是成对成对的,如left.left, right.right ;left.rigth,right.left
boolean isSymmetricalBFS(TreeNode pRoot)
{
if(pRoot == null) return true;
Queue<TreeNode> s = new LinkedList<>();
s.offer(pRoot.left);
s.offer(pRoot.right);
while(!s.isEmpty()) {
TreeNode left= s.poll();//成对取出
TreeNode right= s.poll();
if(left == null && right == null) continue;
if(left == null || right == null) return false;
if(left.val != right.val) return false;
//成对插入
s.offer(left.left);
s.offer(right.right);
s.offer(left.right);
s.offer(right.left);
}
return true;
}