spider68

Check for Balanced Tree

Jun 5th, 2020
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.53 KB | None | 0 0
  1. // This function should return tree if passed  tree
  2. // is balanced, else false.
  3. bool Balanced(Node*root,int *height)
  4. {
  5.     int lh = 0, rh = 0;
  6.     int l = 0, r = 0;
  7.     if (root == NULL) {
  8.         *height = 0;
  9.         return 1;
  10.     }
  11.     l = Balanced(root->left, &lh);
  12.     r = Balanced(root->right, &rh);
  13.     *height = (lh > rh ? lh : rh) + 1;
  14.     if (abs(lh -rh) >= 2)
  15.         return 0;
  16.     else
  17.         return l&&r;
  18. }
  19. bool isBalanced(Node *root)
  20. {
  21.     int height=0;
  22.     return Balanced(root,&height);
  23. }
Add Comment
Please, Sign In to add comment