给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
实现思路:非递归中序遍历二叉搜索树,用一个变量暂存最小值,中序遍历时若后面的比前面的小,则未非二叉搜索树
实现代码:
public static boolean isValidBST(TreeNode root) {
long min = Long.MIN_VALUE; // 此处用long是用来避免同是Integer的最小值
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (root.val <= min) {
return false;
}
min = root.val;
root = root.right;
}
return true;
}
递归实现计算二叉树高度
public static int maxDepth(TreeNode root) {
if (root == null) return 0;
int l = maxDepth(root.left);
int r = maxDepth(root.right);
return l > r ? l + 1 : r + 1;
}
网友评论