数据结构>00 _二叉树练习之平衡二叉树

题源:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/submissions/

一、初始代码:

/**
 * 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 flag=true;
    int p=0;
    int numBalanced(TreeNode *root1){
        int l=0,r=0;
        if (root1->left!=NULL){
            l=1+numBalanced(root1->left);
        }
        if (root1->right!=NULL)
            r=1+numBalanced(root1->right);
        if(l>r)
            p=l-r;
        else
            p=r-l;
        if (p>=2){
            flag=false;
        }
        if(1>r)
            return l;
        else return r;
}
    bool isBalanced(TreeNode* root) {
        
        numBalanced(root);
        return fl

你可能感兴趣的:(数据结构算法笔记)