题意:

image.png

解题思路:

  1. 思路:每个节点仅被遍历一次,且判断的复杂度是 O(1),所以总时间复杂度是 O(n)。
  2. 1. 对于根节点,分别求出左子树和右子树的深度,判断左右子树的高度差是否 <=1
  3. 2. 再对当前节点的左节点和右节点做同样操作。

PHP代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($value) { $this->val = $value; }
  8. * }
  9. */
  10. class Solution {
  11. /**
  12. * @param TreeNode $root
  13. * @return Boolean
  14. */
  15. function isBalanced($root) {
  16. // $this->depthDiff($root);
  17. //return $this->diff < 2;
  18. if ($root == null) return true;
  19. return abs($this->getHeight($root->left) - $this->getHeight($root->right)) <= 1 &&
  20. $this->isBalanced($root->left) && $this->isBalanced($root->right);
  21. }
  22. function getHeight($root) {
  23. if ($root == null) return 0;
  24. $left = $this->getHeight($root->left);
  25. $right = $this->getHeight($root->right);
  26. return max($left, $right) + 1;
  27. }
  28. function depthDiff($root) {
  29. if ($root == null) return 0;
  30. $leftDepth = $this->depthDiff($root->left);
  31. $rightDepth = $this->depthDiff($root->right);
  32. $this->diff = max($this->diff, abs($leftDepth - $rightDepth));
  33. return max($leftDepth, $rightDepth) + 1;
  34. }
  35. }

GO代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func isBalanced(node *TreeNode) bool {
  10. return node == nil || math.Abs(height(node.Left)-height(node.Right)) < 2 && isBalanced(node.Left) && isBalanced(node.Right)
  11. }
  12. func height(node *TreeNode) float64 {
  13. if node == nil { return 0 }
  14. return math.Max(height(node.Left), height(node.Right)) + 1
  15. }