题解 | #对称的二叉树#
对称的二叉树
http://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
1.python 解法:构造递归函数,设置终止条件。递归函数就是左右节点的val相同,而且左节点的右节点和右节点的左节点val相同,左节点的左节点和右节点的右节点val相同,终止条件是节点都不存在返回true,一个节点存在另外一个不存在返回false
class Solution: def isSymmetrical(self, pRoot): # write code here return self.isSame(pRoot, pRoot) def isSame(self, p1, p2): if not p1 and not p2:return True if (p1 and not p2)&nbs***bsp;(p2 and not p1):return False return p1.val == p2.val and self.isSame(p1.left, p2.right) and self.isSame(p1.right, p2.left)
2.java解法:
public class Solution {
boolean isSymmetrical(TreeNode pRoot) {
return isSame(pRoot, pRoot);
}
private boolean isSame(TreeNode p1, TreeNode p2){
if(p1 == null && p2 == null){
return true;
}
if((p1 == null && p2 != null)||(p2 == null && p1 != null)){
return false;
}
return p1.val == p2.val && isSame(p1.left, p2.right) && isSame(p1.right, p2.left);
}
} 3.go解法、
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
func isSymmetrical( pRoot *TreeNode ) bool {
// write code here
return IsSame(pRoot, pRoot)
}
func IsSame( p1 *TreeNode, p2 *TreeNode) bool{
if p1==nil && p2==nil {
return true
}
if (p1==nil && p2!=nil) || (p1!=nil && p2==nil){
return false
}
return p1.Val == p2.Val && IsSame(p1.Left, p2.Right) && IsSame(p1.Right, p2.Left)
}
查看23道真题和解析
