标签:
递归
最简单的理解方法就是如下的思路:
class Solution { public: bool isBalanced(TreeNode* root) { if(root==NULL){ return true; } int ldepth=depth(root->left); int rdepth=depth(root->right); if(abs(ldepth-rdepth)>1)return false; else{ return isBalanced(root->left)&&isBalanced(root->right); } } int depth(TreeNode *root){ if(root==NULL){ return 0; } int lleft=depth(root->left); int trigth=depth(root->right); return lleft>trigth ? lleft+1:trigth+1; } };
在上面的方法中,每一个节点都会计算节点左子树和右子树的高度,存在大量的重复计算
所以,采用自底向上的方式
class Solution2 { public: bool isBalanced(TreeNode* root) { if(root==NULL){ return true; } int height=getheight(root); if(height==-1){ return false; } return true; } int getheight(TreeNode *root){ if(root==NULL){ return 0; } int lleft=getheight(root->left); int trigth=getheight(root->right); if(lleft==-1||trigth==-1){ return -1; } if(abs(lleft-trigth)>1){ return -1; } return lleft>trigth? lleft+1:trigth+1; } };
Balanced Binary Tree --Leetcode C++
标签:
原文地址:http://www.cnblogs.com/hitkb/p/4550184.html