二叉树用递归进行中序遍历是很容易实现的,但是如果能用循环实现的话效率会更好,本人刷题的时候发现了循环写法,故此做下笔记。
理论:
一般的中序遍历代码为:
def bst(root):
if not root:
return
else:
bst(root.left)
return root.val
bst(root.right)
循环写法:
def bst(root):
stack = []
p = root
res = []
while p or stack :
while p:
stack.append(p)
p = p.left
#先把左节点都放在stack中
node = stack.pop()
return node.val
res.append(node.val)
p = node.right
图示说明:
例题1:
实现算法:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if not root: return True
stack = []
cur = root
pre = float("-inf")
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if pre < cur.val:
pre = cur.val
else:
return False
cur = cur.right
return True
例题2:
实现代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:
cur=root
stack=[]
pre=None
while cur or stack:
while cur:
stack.append(cur)
cur=cur.left
cur=stack.pop()
if pre==p:
return cur
else:
pre=cur
cur=cur.right