leetcode : Balanced Binary Tree
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.
比较常规的方法是写一个depth函数求树的深度,然后在写一个递归,分别检验左右子树是不是平衡二叉树,然后在比较左右子树的深度,但是这样做会重复遍历很多次。
可以尝试将求深度的过程加入到二叉树验证的递归函数中,这样只需要遍历一次二叉树
既然要遍历二叉树,转到二叉树的遍历方法:前中后序(dfs),还有层序(bfs)
由于涉及到求子树的深度,即求出深度之后才能判断root是不是平衡的,所以用后序遍历比较合适。
AC代码:
class Solution { public: bool isBalanced(TreeNode *root) { int depth; return postVisit(root, depth); } bool postVisit(TreeNode * root, int &depth){ if(!root){ depth = 0; return true; } int ldep,rdep; bool isLeftBlanced = postVisit(root->left, ldep); bool isRightBlanced = postVisit(root->right, rdep); depth = ldep > rdep ? ldep + 1 : rdep + 1; if(ldep - rdep < -1 || ldep - rdep > 1) return false; else return isLeftBlanced && isRightBlanced; } };
代码中用isLeftBlanced,isRightBlanced储存递归的结果,避免了重复计算postVisit函数。
浙公网安备 33010602011771号