Golden programmer interview - interview questions check the balance of 04.04 (binary tree height)

1. Topic

Implement a function that checks whether a binary tree balanced. In this problem, a balanced tree defined as follows: any node, the height difference between two subtrees which does not exceed 1.

示例 1:
给定二叉树 [3,9,20,null,null,15,7]
    3
   / \
  9  20
    /  \
   15   7
返回 true 。

示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
      1
     / \
    2   2
   / \
  3   3
 / \
4   4
返回 false

2. Problem Solving

class Solution {
public:
    bool isBalanced(TreeNode* root) {
    	bool ans = true;
    	check(root, ans);
    	return ans;
    }

    int check(TreeNode* root, bool& bal)
    {
    	if(!root || !bal)
    		return 0;
    	int l = check(root->left, bal);
    	int r = check(root->right, bal);
    	if(abs(l-r)>1)
    		bal = false;
    	return max(l,r)+1;
    }
};

Here Insert Picture Description

Published 748 original articles · won praise 921 · views 260 000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105001539