6.10 leetcode 二叉树的最大深度, 验证二叉搜索树

验证二叉搜索树

//方法一:递归 时间O(n) 空间递归用栈空间O(n)
public boolean isValidBST(TreeNode root) {
	return (root, null, null);
}

public boolean recurse(TreeNode node, Integer lower, Integer upper) {
	if (node == null) {
		return true; 
	}
	int value = node.val;
	if (lower != null && val <= lower) return false;
	if (upper != null && val >= upper) return false;
	
	if (!recurse(node.right, val, upper)) return false;
	if (!recurse(node.left, lower, val)) return false;
	return true;
	
}

//方法二: 中序遍历 栈  时间O(n) , 空间O(n) 开辟的stack
public boolean isValidBST(TreeNode root) {
	Stack<TreeNode> stack = new Stack();
	Integer inorder = null;
	while (!stack.isEmpty() || root != null) {
		while (root != null) {
			stack.push(root);
			root = root.left;
		}
		root = stack.pop();
		if (inorder != null && root.val <= inorder) return false;
		inorder = root.val;
		root = root.right;
	}
	return true;
}
二叉树最大深度
// 方法一: 递归: 时O(n) ,空O(n)
 public int maxDepth(TreeNode root) {
        if (null == root) return 0;
        int maxDepth = Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
        return maxDepth;
    }


// 方法二 栈  迭代 :时O(n) ,空O(n)
 public int maxDepth(TreeNode root) {
        Queue<Pair<TreeNode, Integer>> stack = new LinkedList<>();
        if (root != null) {
            stack.add(new Pair(root, 1));
        }
        int depth = 0;
        while (!stack.isEmpty()) {
            Pair<TreeNode, Integer> current = stack.poll();
             TreeNode node = current.getKey();
            int currentDepth = current.getValue();
            if (node != null) {
                depth = Math.max(depth, currentDepth);
                stack.add(new Pair(node.left, currentDepth + 1));
                stack.add(new Pair(node.right, currentDepth + 1));
            }
        }
        return depth;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值