leetcode(34): 判断平衡二叉树

    科技2025-04-14  12

    文章目录

    题目描述法一:自顶向下的递归 O(n^2)法二:自底向上的递归 O(n)总结

    //经典leetcode简单题。。。

    题目描述

    法一:自顶向下的递归 O(n^2)

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int height(TreeNode *root){ if(root == NULL) return 0; return max(height(root->left), height(root->right)) + 1; } bool isBalanced(TreeNode* root) { if(root == NULL) return true; return abs(height(root->left) - height(root->right) <= 1) && isBalanced(root->left) && isBalanced(root->right); } };

    简写

    class Solution { public: bool isBalanced(TreeNode* root) { return !root ? true : abs(depth(root->left) - depth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right); } int depth(TreeNode* cur) { //计算最大深度 return !cur ? 0 : max(depth(cur->left), depth(cur->right)) + 1; } };

    法二:自底向上的递归 O(n)

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: //确定函数功能:放入一个根节点,先求出其左右子树的高度,来判断该根节点是否为平衡树,是则返回高度(非负数),否则返回-1 //确定尾头:尾 root == null ; 头 int rightOrNot(TreeNode *root){ if(root== NULL) return 0; int leftHeight = rightOrNot(root->left); int rightHeight =rightOrNot(root->right); if(leftHeight == -1 || rightHeight == -1 || abs(leftHeight - rightHeight) > 1) return -1; else return max(leftHeight, rightHeight) + 1; } bool isBalanced(TreeNode* root) { return rightOrNot(root) >= 0; } };

    总结

    树的递归相关题,盯着他的子树做文章

    Processed: 0.009, SQL: 8