题目描述
请实现一个函数,用来判断一棵二叉树是不是对称的。
如果一棵二叉树和它的镜像一样,那么它是对称的。
样例
如下图所示二叉树[1,2,2,3,4,4,3,null,null,null,null,null,null,null,null]为对称二叉树: 1 / \ 2 2 / \ / \ 3 4 4 3 如下图所示二叉树[1,2,2,null,4,4,3,null,null,null,null,null,null]不是对称二叉树: 1 / \ 2 2 \ / \ 4 4 3
一、递归解法:
1.只要pRoot.left和pRoot.right是否对称即可
2.左右节点的值相等 且 对称子树left.left, right.right ; left.rigth,right.left也对称
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { boolean isSymmetrical(TreeNode pRoot) { if(pRoot == null){ return true; } return isSymmetrical(pRoot.left, pRoot.right); } private boolean isSymmetrical(TreeNode left, TreeNode right){ if(left==null && right==null) return true; if(left==null || right==null) return false; return (left.val == right.val) && isSymmetrical(left.left, right.right) && isSymmetrical(left.right, right.left); } }
二、非递归DFS栈式计算
DFS使用stack来保存成对的节点
1.
出栈的时候也是
成对成对的 ,
1.若都为空,继续;
2.一个为空,返回false;
3.不为空,比较当前值,值不等,返回false;
2.确定入栈顺序,每次
入栈都是成对
成对的,如left.left, right.right ;left.rigth,right.left
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.Stack; public class Solution { boolean isSymmetrical(TreeNode pRoot) { if(pRoot == null){ return true; } Stack<TreeNode> stack = new Stack<>(); stack.push(pRoot.left); stack.push(pRoot.right); while(!stack.isEmpty()){ TreeNode right = stack.pop(); //成对取出 TreeNode left = stack.pop(); if(right==null && left==null) continue; // if(right==null || left==null) return false; if(right.val != left.val) return false; //成对插入 stack.push(left.left); stack.push(right.right); stack.push(left.right); stack.push(right.left); } return true; } }
三、非递归DFS栈式计算
1.
出队的时候也是成对成对的
1.若都为空,继续;
2.一个为空,返回false;
3.不为空,比较当前值,值不等,返回false;
2.确定入队顺序,
每次入队都是成对成对的,如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; }