leetcode daily brush title plan - simple articles day17

Hee hee hee made in advance to calculate a new day, eat barbecue giant happy ah

Num 110 balanced binary tree

Note that each layer must balance the job, just remember the beginning of the judgment root

/**
 * 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==NULL) return true;
        if(abs(getLevel(root->left)-getLevel(root->right))>1) 
           return false;
        return (isBalanced(root->left) && isBalanced(root->right));
    }
    int getLevel(TreeNode*root)
    {
        if(root==NULL) return 0;
        return max(getLevel(root->left),getLevel(root->right))+1;
    }
};
View Code

 Num minimum depth of the binary tree 111

The question is not difficult but still not right the first time, this is the shortest seek depth, note that if there is no left a bit to the right, this time not as a right is 0. For example, [1,2] is a two-story, note in solving problems related to the tree.

First, note that the root is not determined, second, taking into account of null nodes and leaf nodes

/**
 * 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 minDepth(TreeNode* root) {
        if(root==NULL) return 0;
        if(root->left==NULL && root->right==NULL) return 1;
        if(root->left==NULL) return minDepth(root->right)+1;
        if(root->right==NULL) return minDepth(root->left)+1;
        return min(minDepth(root->left),minDepth(root->right))+1;
    }
};
View Code

 

Guess you like

Origin www.cnblogs.com/tingxilin/p/11141287.html