1,递归
条件是,两个叶子的值相当,左叶子的左叶子值等于右叶子的右叶子,左叶子的右叶子等于右叶子,空节点自然对称
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root==null){
return true;
}
return symmetric(root.left,root.right);
}
private boolean symmetric(TreeNode left, TreeNode right){
if(left==null&&right==null){
return true;
}
if(left==null||right==null){
return false;
}
return ( (left.val==right.val)&&symmetric(left.left,right.right)&&symmetric(left.right,right.left) );
}
}另一种思路是用栈,这个只能自己多化几次图看看就明白了:
public boolean isSymmetric(TreeNode root) {
if(root==null){
return true;
}
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode pleft=root.left;
TreeNode pright=root.right;
stack.push(pleft);
stack.push(pright);
while(!stack.empty()){
pleft=stack.pop();
pright=stack.pop();
if(pleft==null&&pright==null){
continue;
}
if(pleft==null||pright==null){
return false;
}
if(pleft.val!=pright.val){
return false;
}
stack.push(pleft.left);
stack.push(pright.right);
stack.push(pleft.right);
stack.push(pright.left);
}
return true;
}

402

被折叠的 条评论
为什么被折叠?



