Problem:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the Every node never differ by more than 1.
Hide TagsTree Depth-first SearchTest instructions: Judging whether a binary tree is a balanced binary tree
Thinking:
(1) This problem is very simple, but the careful study found that the balance of binary tree understanding is wrong: the maximum depth of the left and right sub-tree (that is, the height of the tree) is not more than 1,
Not specifically the height of each leaf node, the height of the tree. I started out by finding the height of each leaf node, and then comparing it to the definition of a balanced binary tree.
(2) The exact idea is to judge the left and right sub-trees at each time by recursion.
Code
Wrong idea:
Class Solution { private: vector<int> depth; Public: bool isbalanced (TreeNode *root) { if (root==null) return true; DFS (0,root); Sort (Depth.begin (), Depth.end ()); if (* (Depth.end ()-1)-depth[0]>1) return false; else return true; } Protected: void dfs (int dep,treenode *node) { if (node==null) { cout<<dep<< Endl; Depth.push_back (DEP); return; } dep++; DFS (dep,node->left); DFS (dep,node->right); } };
Correct answer:
Class Solution {public : bool isbalanced (TreeNode *root) { int depth = 0; return isbalance (root, depth); } BOOL Isbalance (TreeNode *root, int &depth) { if (root = = NULL) { depth = 0; return true; } int ld,rd; if (Isbalance (root->left,ld) && isbalance (root->right,rd)) { if (ABS (LD-RD) > 1) { C17/>return false; } depth = ld > RD? LD + 1:RD + 1; return true;}} ;
Leetcode | | 110. Balanced Binary Tree