Test instructions: Title, the balance tree refers to any one node (except the leaves), the height of its left subtree and the height of the right sub-tree is not more than 1.
Idea: recursive solution, but the function provided does not meet the requirements of recursion Ah, we have to know at least the height, but also to return to true and false, so another function to solve.
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A BOOLAns//The answer will be recorded here. - intDFS (treenode*root) - { the if(!root | |!ans)return 0;//It 's wrong, no need to compare - intB=dfs (root->Right ); - intA=dfs (root->Left ); - if(ABS (a) >1) ans=false; + returnMax (A, B) +1; - } + A BOOLIsbalanced (treenode*root) { atans=true;//Initialize Answer - DFS (root); - returnans; - } -};
AC Code
Leetcode Balanced Binary tree (judging balance trees)