1、如果需要考虑之前的状态就可以使用有限状态机
有限状态机:
Leecode 第8题:
class A: def __init__(self): self.sign=1 self.ans=0 self.currentState="empty" self.dict={ "empty":["empty","sign","digit","end"], "sign":["end","end","digit","end"], "digit":["end","end","digit","end"], "end":["end","end","end","end"] } def tocondition(self,s:str,i:int): # 条件转化为数字 if s[i]==' ': return 0 elif s[i]=='+' or s[i]=='-': return 1 elif s[i].isdigit(): return 2 else: return 3 def deal(self,s:str,i:int): condition = self.tocondition(s,i) self.currentState=self.dict[self.currentState][condition] if self.currentState=="sign": self.sign = -1 if s[i]=='-' else 1 if self.currentState=='digit': self.ans=self.ans*10+int(s[i]) class Solution: def myAtoi(self, s: str) -> int: a = A() for i in range(len(s)): a.deal(s,i) res = a.sign * a.ans if res<-2**31: res=-2**31 if res>2**31-1: res=2**31-1 return res
2、非递归先序遍历
准备一个栈,然后访问根节点,入栈,走到左子树,访问,入栈,左子树没了访问不了,出栈一个元素,走到它的右子树,访问根节点...直到访问不了且栈空了(想用刚刚的元素,就可以想到栈)
stack = [] while root or len(stack)!=0: if root: print(root.val) stack.append(root) root=root.left else: root = stack.pop() root = root.right
2、层次序列生成二叉树
对当前节点,给他左边加节点,然后入队,右边加节点,然后入队,出队一个元素,对该元素左边加节点...(想到用老之前的元素,就可以想到队列)
def create(self,nums): # 层次建立二叉树 root = Node(nums[0]) q = queue.Queue(len(nums)) q.put(root) i = 1 while i<=len(nums): if nums[i]=='null': i+=1 continue node = q.get() node.left = Node(nums[i]) q.put(node.left) i+=1 if i==len(nums): break if nums[i]=='null': i+=1 continue node.right = Node(nums[i]) q.put(node.right) i+=1 return root def mid(self,root): # 非递归中序遍历 stack = [] while root or len(stack)!=0: if root: stack.append(root) root=root.left else: top = stack.pop() print(top.val) root = top.right def pre(self,root): # 非递归先序遍历 stack = [] while root or len(stack)!=0: if root: print(root.val) stack.append(root) root=root.left else: root = stack.pop() root = root.right
3
标签:digit,end,self,sign,力扣,return,root From: https://www.cnblogs.com/pjishu/p/16739869.html