LeetCode做题总结:二叉树

本文介绍了一种计算二叉树最大深度的方法,并实现了一个判断二叉树是否为二叉搜索树(BST)的算法。通过递归方式,我们能够有效地遍历树的每个节点,计算其深度并验证BST属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Solution15 {
	public int maxDepth(TreeNode root) {
    if(root==null)   return 0;
    else return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
	}
	public static void main(String args[]){
     Solution15 solution15=new Solution15();
     TreeNode root=new TreeNode(3);
     //TreeNode l1=new TreeNode(4);
     root.left=new TreeNode(4);
     root.right=new TreeNode(5);
     root.left.left=new TreeNode(6);
     root.left.right=new TreeNode(7);
     root.right.left=new TreeNode(8);
		System.out.println(solution15.maxDepth(root));
	}
}
public class ListNode{
	int val;
	ListNode next;
	ListNode(int x)  {val=x;}
}

 

 

public boolean isValidBST(TreeNode root) {
      if(root==null)   return true;
      return helper(root,null,null);
	}
	public boolean helper(TreeNode root,Integer max,Integer min){
    if(root==null)  return true;
    if(max!=null&&root.val>=max)   return false;
    if(min!=null&&root.val<=min)   return false;
    return helper(root.left,root.val,min)&&
			helper(root.right,max,root.val);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值