c++实现递归和非递归判断一颗二叉树是否是平衡二叉树

c++实现递归和非递归判断一颗二叉树是否是平衡二叉树

struct TreeNode {
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int v):val(v),left(nullptr), right(nullptr) {}
}

// 递归形式
int getHeight(TreeNode *root) {
  if(!root) return 0;
  int left = getHeight(root->left);
  int right = getHeight(root—>right);
  return left > right ? left+1 :right+1;
}

bool isBalanced(TreeNode *root) {
  if(!root) return true;
  int leftDep = getHeight(root->left);
  int rightDep = getHeight(root->right);
  if(abs(leftDep - rightDep) > 1) {
    return false;
  }
  return isBalanced(root->left) && isBalanced(root->right);
}


// 非递归形式

bool isBalanced(TreeNode *root) {
  if(!root) return false;
   queue<TreeNode *> que;
   que.push(root);
   while(!que.empty()) {
    TreeNode *tempNode = que.front();
    que.pop();
    int leftDepth = getHeight(tempNode->left);
    int rightDepth = getHeight(tempNode->right);
    if(abs(leftDepth - rightDepth) > 1) {
      return false;
    }
    if(tempNode->left) que.push(tempNode->left);
    if(tempNode->right) que.push(tempNode->right);
   }
   return true;

}

你可能感兴趣的:(c++,java,算法)