Balanced Binary Tree - LeetCode
发布时间:2020-12-14 04:36:11 所属栏目:大数据 来源:网络整理
导读:目录 题目链接 注意点 解法 小结 题目链接 Balanced Binary Tree - LeetCode 注意点 不要访问空结点 解法 解法一: getDep 用于求各个点深度的,然后对每个节点的两个子树来比较深度差,时间复杂度为O(NlgN)。 /** * Definition for a binary tree node. * s
目录
题目链接Balanced Binary Tree - LeetCode 注意点
解法解法一: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x),left(NULL),right(NULL) {} * }; */ class Solution { public: int getDep(TreeNode* root) { if (!root) return 0; return 1 + max(getDep(root->left),getDep(root->right)); } bool isBalanced(TreeNode* root) { if(!root) return true; if(abs(getDep(root->left)-getDep(root->right)) > 1) return false; return isBalanced(root->left) && isBalanced(root->right); } }; 小结
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |