标签:http info post lse 高度 roo color lan logs
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
来源:力扣(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: bool isBalanced(TreeNode* root) { int depth = 0; return isBalancedCore(root, depth); } bool isBalancedCore(TreeNode* root, int& depth) //计算某个节点的左右子树深度 { if (root == nullptr) { depth = 0; return true; } int left, right; if (isBalancedCore(root->left, left) && isBalancedCore(root->right, right)) { int dif = left - right; if (dif <= 1 && dif >= -1) { depth = (left > right) ? left + 1 : right + 1; return true; } } return false; } };
解法二:多次遍历
/** * 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: bool isBalanced(TreeNode* root) { if (root == nullptr) return true; int left = treeDepth(root->left); int right = treeDepth(root->right); int dif = left - right; if (dif < -1 || dif > 1) return false; return isBalanced(root->left) && isBalanced(root->right); } int treeDepth(TreeNode* root) { if (root == nullptr) return 0; int left = treeDepth(root->left); int right = treeDepth(root->right); return (left > right) ? left + 1 : right + 1; } };
LeetCode 110. 平衡二叉树 Balanced Binary Tree (Easy)
标签:http info post lse 高度 roo color lan logs
原文地址:https://www.cnblogs.com/ZSY-blog/p/12827131.html