栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode算法学习笔记 - Day9

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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);
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/690288.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号