leetcode 每日一题 94. 二叉树的中序遍历
递归
思路:
先遍历左子树,再访问根节点,再遍历右子树。
代码:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: def helper(root,res): if root: if root.left: helper(root.left,res) res.append(root.val) if root.right: helper(root.right,res) res = [] helper(root,res) return res
迭代
思路:
创建一个栈,从根节点遍历左子树,将对应根节点和左子树压入栈中,直到左子树为空。此时取出栈顶节点,将对应节点的值记录,继续对取出节点的右子树进行压栈和取出记录操作,取出的栈顶元素如果右子树为空,则记录后继续取出栈顶节点。
代码:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] stack = [] cur = root while cur or stack: while cur: stack.append(cur) cur = cur.left cur = stack.pop() res.append(cur.val) cur = cur.right return res
线索二叉树
思路:
创建两个指针cur和pre,分别代表当前节点,和当前节点的前驱,由中序遍历的性质得:
①如果cur没有左子节点,将cur的val添加到输出,继续遍历右子树即cur = cur.right
②如果cur有左子节点,则找到左子树的最右侧节点的右子节点为pre,记录cur的左子节点temp,令cur的左子节点为空,pre的右子节点为cur,cur变为temp
只要cur不为空就继续①②操作
例如:
代码:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] cur,pre = root,None while cur: if not cur.left: res.append(cur.val) cur = cur.right else: pre = cur.left while pre.right: pre = pre.right pre.right = cur temp = cur cur = cur.left temp.left = None return res
线索二叉树:(不改变树的结构)
思路:
在上面二叉树线索二叉树的基础上,可以在当前节点cur和当前节点的前驱pre之间设置一个临时的链接:pre.right = cur。在当前cur节点找它的前驱pre时:
①如果没有链接,设置链接并走向左子树,pre.right = cur , cur = cur.left
②如果有链接,断开链接并走向右子树,pre.right = None , cur = cur.right
代码:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] cur,pre = root,None while cur: if not cur.left: res.append(cur.val) cur = cur.right else: pre = cur.left while pre.right and pre.right!=cur: pre = pre.right if pre.right is None: pre.right = cur cur = cur.left else: res.append(cur.val) pre.right = None cur = cur.right return res