def longestConsecutive(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(parent, root, length):
if not root:
return length
if root.valparent.val == 1:
length += 1
else:
length = 1
return max(length, helper(root, root.left, length), helper(root, root.right, length))
if not root:
return 0
return max( helper(root, root.left, 1), helper(root, root.right, 1))
S
shawn2010
@shawn2010
8
Reputation
19
Posts
255
Profile views
0
Followers
0
Following
Posts made by shawn2010

Python DFSdon't need global variable

RE: Python O(n) solution using sets
num is converted into a set, so each "i in num" is now O(1)

Python recursive solution for Basic Calculator
Use calculateBracket to calculate an expression within a bracket, and return the value from this expression within bracket, also return the position after the ending bracket.
Recursively call calculateBracket() whenever we see a "(".
Return whenever we meet a ")", this way we always match each "(" and its ending ")"def calculate(self, s): """ :type s: str :rtype: int """ def calculateBracket(expression, leftStartIndex): pos = leftStartIndex res = 0 sign = "+" while pos < len(expression) and expression[pos] != ")": tempRes = 0 if expression[pos] == "(": pos, tempRes = calculateBracket(expression, pos+1) else: if expression[pos].isdigit(): while pos<len(expression) and expression[pos].isdigit(): tempRes = tempRes*10 + int(expression[pos]) pos += 1 else: if expression[pos] == "+" or expression[pos] == "": sign = expression[pos] pos += 1 if sign == "+": res += tempRes elif sign == "": res = tempRes return pos+1, res pos, result = calculateBracket(s, 0) return result

RE: Java BFS SolutionO(mn) Time
you are right but also keep in mind that the matrix has m * n entries.

RE: My short java solution, very easy to understand
I think time complexity should be O(mn) since each entry will be visited at most 4 times which means O(4mn)