题解 | #对称的二叉树#

对称的二叉树

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)
}


全部评论

相关推荐

点赞 评论 收藏
分享
身边有人上海、深圳 6、7k 都去了,真就带薪上班了。
程序员小白条:木的办法, 以后越来越差,还是家附近宅着吧,毕业的人越来越多,岗位都提供不出来,经济又过了人口红利期
点赞 评论 收藏
分享
小浪_Coding:找硬件测试,也可兼顾软测欧, 简历还可以的 ,注意排版,项目写的有条理一点, 然后个人技能多加点, 润色好简历之后就开始沟通海投了,深圳,东莞这边做硬件相关的公司还不少, 医疗类,仪器类的都可以尝试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务