标签:div content roo class get 多次 evel sub return
1 //方法一:使用深度遍历,判断每个节点是不是平衡二叉树,这种从上至下的方法会导致底层的节点重复判断多次 2 class Solution01 { 3 public: 4 bool IsBalanced_Solution(TreeNode* pRoot) { 5 if (pRoot == nullptr)return true; 6 int left = getHeight(pRoot->left); 7 int right = getHeight(pRoot->right); 8 if (abs(left - right) > 1)return false; 9 return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right); 10 } 11 private: 12 int getHeight(TreeNode *pRoot) 13 { 14 if (pRoot == nullptr)return 1; 15 int left = getHeight(pRoot->left); 16 int right = getHeight(pRoot->right); 17 return max(left, right) + 1; 18 } 19 }; 20 21 //方法二:使用后序遍历判断,这种方法为自下而上,每个节点只需要判断一次即可 22 class Solution02 { 23 public: 24 bool IsBalanced_Solution(TreeNode* pRoot) { 25 if (pRoot == nullptr)return true; 26 int level = 0; 27 return IsBalanced_Solution(pRoot, level); 28 } 29 private: 30 bool IsBalanced_Solution(TreeNode* pRoot, int &level) 31 { 32 if (pRoot == nullptr) 33 { 34 level = 0; 35 return true; 36 } 37 //按照后序遍历去判断左右子树,然后以当前节点为根树的深度 38 int left = 0, right = 0; 39 if (IsBalanced_Solution(pRoot->left, left) && IsBalanced_Solution(pRoot->right, right)) 40 { 41 if (abs(left - right) <= 1) 42 { 43 level = max(left, right) + 1; 44 return true; 45 } 46 } 47 return false; 48 } 49 };
标签:div content roo class get 多次 evel sub return
原文地址:https://www.cnblogs.com/zzw1024/p/11707121.html