【二叉树】判断二叉树是否为平衡二叉树

xiaoxiao2021-02-28  70

题目链接:https://leetcode.com/problems/balanced-binary-tree/#/description

/** * 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(checkDepth(root)==-1) return false; else return true; } // 计算节点层数,并判断是否为平衡树 int checkDepth(TreeNode* root){ if(root==NULL) return 0; // 左儿子节点层数 int l=checkDepth(root->left); if(l==-1) return -1; // 右儿子节点层数 int r=checkDepth(root->right); if(r==-1) return -1; // 判断是否平衡 int diff=abs(l-r); if(diff>1) return -1; // 返回最大层数 return 1+max(l,r); } };

转载请注明原文地址: https://www.6miu.com/read-82958.html

最新回复(0)