二叉树的高度

  • 二叉树的高度为:叶子节点到根节点的路径上的节点数。

  • 二叉树的深度是从根节点开始(其深度为1)自顶向下逐层累加的;而二叉树高度是从叶节点开始(其高度为1)自底向上逐层累加的。虽然树的深度和高度一样,但是具体到树的某个节点,其深度和高度是不一样

判断平衡二叉树

  1. int getDepth(TreeNode* node) {
  2. if (node == NULL) return 0;
  3. int leftDepth = getDepth(node->left);
  4. if (leftDepth == -1) return -1;
  5. int rightDepth = getDepth(node->right);
  6. if (rightDepth == -1) return -1;
  7. return abs(leftDepth - rightDepth) > 1 ? -1 : 1 + max(leftDepth, rightDepth);
  8. }