objectSolution{ defisBalanced(root: TreeNode): Boolean = { if (root == null) { returntrue } var abs = Math.abs(getDepth(root.left) - getDepth(root.right)) if (abs <= 1 && isBalanced(root.left) && isBalanced(root.right)){ returntrue } returnfalse
} defgetDepth(root:TreeNode): Int = { if (root==null) { return0 } var left = getDepth(root.left) var right = getDepth(root.right) returnMath.max(left, right) + 1 } }
objectSolution{ var seq = Seq[Int]() definOrder(root: TreeNode):Unit = { if(root != null) { inOrder(root.left) seq = seq :+ root.value inOrder(root.right) } } defisValidBST(root: TreeNode): Boolean = { inOrder(root) if (seq.length == 0){ returntrue } if (seq.length == 1){ returntrue } for (i <- 0 until seq.length-1) { if (seq(i) >= seq(i+1)){ returnfalse } } returntrue
} }
二叉搜索树的下一个结点
遍历元素放入列表,查找列表。
1 2 3 4 5 6 7 8 9 10 11 12 13
class Solution: def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode: if root: if p.val >= root.val: return self.inorderSuccessor(root.right,p) else: a = self.inorderSuccessor(root.left,p) if a is None: return root else: return a return None