0424: 13, balanced binary tree; 14, and the number of columns of consecutive positive S;

13, balanced binary tree

Description Title
input binary tree, the binary tree is determined whether a balanced binary tree.
Note: the depth calculation involving binary tree, using a recursive

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def IsBalanced_Solution(self, pRoot):
        # write code here
        if pRoot == None:
            return True
        if abs(self.TreeDepth(pRoot.left)-self.TreeDepth(pRoot.right)) > 1:
            return False
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
    def TreeDepth(self,pRoot):
        if pRoot == None:
            return 0
        nleft = self.TreeDepth(pRoot.left)
        nright = self.TreeDepth(pRoot.right)
        return max(nleft + 1, nright + 1)

14, and a continuous positive number of columns S

Title Description
When Xiao Ming is very fond of mathematics, one day he was doing math homework, required to calculate and 9 to 16, he immediately wrote the correct answer is 100. But he was not satisfied with this, he wondered how many kinds of continuous positive number sequence is 100 (including at least two numbers). Before long, he got another set of consecutive positive number and a sequence of 100: 18,19,20,21,22. Now the question to you, you can also quickly identify all positive and continuous sequence S Good Luck?!
Output Description:

All positive output and a continuous number sequence S. The sequence in the order of small to large, from small to large inter-sequence starts in the order numbers
Note: how to determine the range would not cycle, read back resolution, but the maximum value of n is taken and circulation half plus 1, more thinking -
a first modification to obtain for themselves, and the second is the code by the

class Solution:
    def FindContinuousSequence(self, tsum):
        # write code here
        n = 2
        res = []
        while n <= tsum/2+1:
            a = (tsum - n * (n - 1) / 2) % n
            b = (tsum - n * (n - 1) / 2) / n
            if a == 0 and b > 0:
                res.append(range(b,b+n))
            n += 1
        return res[::-1]

Method 2:

# -*- coding:utf-8 -*-
class Solution:
    def FindContinuousSequence(self, tsum):
        # write code here
        res=[]
        for i in range(1,tsum/2+1):
            for j in range(i,tsum/2+2):
                tmp=(j+i)*(j-i+1)/2
                if tmp>tsum:
                    break
                elif tmp==tsum:
                    res.append(range(i,j+1))
        return res

Guess you like

Origin blog.csdn.net/Leia21/article/details/89540374