LeetCode算法学习笔记 - Day9

二叉树的最大深度

  • 给定一个二叉树,找出其最大深度。
  • 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
    这题我的解题思路是层级遍历每一层,遍历到下一层层数i就+1 || 或者是前序遍历,在外部定义一个height 遍历到底部就与height对比
    最后发现代码太累赘了根本没写,直接借用别人的代码 出处
	public int maxDepth(Node node){
        if(node == null){
            return 0;
        }else {
            int left = maxDepth(node.left);
            int right = maxDepth(node.right);
            return left > right ? (left + 1) : (right + 1);
        }
    }

对称二叉树

  • 给定一个二叉树,检查它是否是镜像对称的。
    这题不会做,看看半成品吧
	public boolean isSymmetric(){
        if (root.left == null && root.right == null){
            return true;
        }
        return isSymmetric(root);
    }
    private boolean isSymmetric(Node node){
        if (node.left == null || node.right == null){
            return false;
        }
        if (node.left.left == null && node.left.right == null && node.right.left == null && node.right.right == null){
            return true;
        }
        Node leftA = node.left.left;
        Node rightA = node.right.right;
        Node rightB = node.left.right;
        Node leftB = node.right.left;
        boolean booleanA = false;
        boolean booleanB = false;
        if (leftA != null && rightA != null && leftA.data == rightA.data){
            booleanA = isSymmetric(node.left);
        }
        if (leftB != null && rightB != null && leftB.data == rightB.data){
            booleanB = isSymmetric(node.right);
        }
        if (!booleanA || !booleanB) {
            return false;
        }
        return true;
    }

路径总和

  • 给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值 相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。

题目没搞明白,但是具体功能已完成(当root只有一个或者root只有左右子树时LeetCode不给过)(当树高度超过3一切正常)

	private boolean hasPathSum(Node node,int targetSum,int nowSum){
        if (node == null){
            return false;
        }
        if (node.data + nowSum == targetSum){
            return true;
        }else {
            boolean A = hasPathSum(node.left,targetSum,node.data + nowSum);
            boolean B = hasPathSum(node.right,targetSum,node.data + nowSum);
            if (A == true || B == true){
                return true;
            }
        }
        return false;
    }
    public boolean hasPathSum(int targetSum) {
        return hasPathSum(root,targetSum,0);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值