二叉树-28最大深度29二叉树路径和

28.求二叉树最大深度

在这里插入图片描述
思路就是和层次遍历一样,只是不需要数组存对应的值,只要记录层数即可,还是用队列,时间复杂度和空间复杂度都是O(n)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if(root==null) return 0;
        Deque<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        int lay = 0;
        while(!q.isEmpty()){
            int count = q.size();//每一层的个数         
            while(count-- >0){
                TreeNode node = q.poll();
                if(node.left!=null) q.offer(node.left);
                if(node.right!=null) q.offer(node.right);
            }
            lay++;           
        }
        return lay;
    }
}

第二种用递归的方法,树的深度=max(左子树深度,右子树深度)+1
代码十分简洁,时间复杂度和空间复杂度都是O(n)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        if(root==null) return 0;
        return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
    }
}

29. 二叉树中和为某一值的路径(一)

在这里插入图片描述
在这里插入图片描述
用递归判断,错了好几次,错在边界条件的判断,要注意两点:

  • 路径一定是要到叶节点的,到中间某个节点相等也是不行的
  • 数据包含负数,不能用val>sum作为返回false的边界条件

时间复杂度和空间复杂度都是O(N)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    public boolean hasPathSum (TreeNode root, int sum) {
        // write code here
        if(root==null) return false;
        if(root.val==sum){
            //还没到叶节点就相等了也不行
            if(root.left==null&&root.right==null) return true;
        }
        return hasPathSum(root.left, sum-root.val)||hasPathSum(root.right,sum-root.val);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值