Leetcode 110. Balanced Binary Tree

xiaoxiao2021-02-28  25

原题:

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

3 / \ 9 20 / \ 15 7

Return true.Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

1 / \ 2 2 / \ 3 3 / \ 4 4

Return false.

解决方法:

依然可以用递归。

这里写了一个新函数,返回结果在函数函数参数里面返回,函数返回值返回数的深度。这样的写法在以后的解法中会多次用到。

代码: int getDepth(TreeNode* root, bool& res){ if (!root){ res = true; return 0; } bool leftMatch = false, rightMatch = false; int left = getDepth(root->left, leftMatch), right = getDepth(root->right, rightMatch) ; res = leftMatch && rightMatch &&(abs(left - right) <= 1) ; return 1 + max(left, right); } bool isBalanced(TreeNode* root) { bool res = false; getDepth(root, res); return res; }
转载请注明原文地址: https://www.6miu.com/read-1949968.html

最新回复(0)