对称的二叉树
对称的二叉树
http://www.nowcoder.com/questionTerminal/ff05d44dfdb04e1d83bdbdab320efbcb
思路:
- 当根节点为null时,返回true
- 当根节点不为空时,定义两个指针root1,root2分别指向根节点的左和右节点
- 当root1.left==root2.right和root1.right==root2.left同时为true时,返回true,否则为false。同时设置递归的终止条件:当两者同时为null说明两者上一个都是叶子节点且比对成功;当两者不同时为null即只有一方为null时,说明没有比对成功返回false。
/*
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 solve(pRoot.left,pRoot.right);
}
public static boolean solve(TreeNode root1,TreeNode root2){
//递归终止条件
if(root1==null && root2 == null){
//当叶子节点都相同时,返回true
return true;
}
if(root1 == null || root2 ==null){
//当两个不同时为空时,返回false
return false;
}
if(root1.val!=root2.val){
return false;
}
boolean flag1 = solve(root1.left,root2.right);
boolean flag2 = flag1?solve(root1.right,root2.left):false;//flag1为true返回前面的,为false返回false
return flag1 && flag2;
}
}
安克创新 Anker公司福利 810人发布
