# LeetCode 对称二叉树

## 2.初解题思路(代码语言:Java)

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {

Stack<Integer> leftStack = new Stack<Integer>();
Stack<Integer> rightStack = new Stack<Integer>();

public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
getLeftOrder(root.left);
getRightOrder(root.right);
while(!leftStack.isEmpty() && !rightStack.isEmpty()){
int leftVal = leftStack.pop().intValue();
int rightVal = rightStack.pop().intValue();
if(leftVal!=rightVal){
return false;
}
}
return leftStack.isEmpty() && rightStack.isEmpty();
}

public void getLeftOrder(TreeNode root){
if(root!=null){
leftStack.push(new Integer(root.val));
getLeftOrder(root.left);
getLeftOrder(root.right);
}else{
leftStack.push(new Integer(0));
}
}

public void getRightOrder(TreeNode root){
if(root!=null){
rightStack.push(new Integer(root.val));
getRightOrder(root.right);
getRightOrder(root.left);
}else{
rightStack.push(new Integer(0));
}
}

}


## 3.双指针+递归思路

/**
* 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 check(root.left,root.right);
}

public boolean check(TreeNode left,TreeNode right){
if( left == null && right == null ){
return true;
}
if( left == null || right == null ){
return false;
}
return (left.val == right.val) &&
check(left.left,right.right) &&
check(left.right,right.left);
}
}


## 对比两者

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

jiachengren

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
08-14 117

11-28 220
08-26 230
09-01 193
08-16 250
05-16 1982
06-09 215