public List<Integer> preorderTraversal(TreeNode root){ List<Integer> res = new ArrayList<Integer>(); if (root == null) { return res; } Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while (!stack.isEmpty()) { TreeNode node = stack.pop(); res.add(node.val); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } return res; }
迭代算法版本2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public List<Integer> preorderTraversal(TreeNode root){ List < Integer > res = new ArrayList <> (); Stack < TreeNode > stack = new Stack <> (); TreeNode curr = root; while (curr != null || !stack.isEmpty()) { while (curr != null) { res.add(curr.val); stack.push(curr); curr = curr.left; } curr = stack.pop(); curr = curr.right; } return res; }
莫里斯遍历
先看中序遍历的莫里斯遍历
Step 1: 将当前节点current初始化为根节点 Step 2: While current不为空 ①若current没有左子节点 a. 将current添加到输出 b. 进入右子树,亦即, current = current.right ②否则进入current的左子树中,找到“右子节点为空或者即使不为空也要不等于当前节点”的最右侧节点
如果最右侧结点为空,说明不是因为最右侧结点已经建立后继节点而退出while循环的
a. 将当前节点输出,并设置最右侧节点的右子节点(后继节点)为current b. 进入左子树,亦即,current = current.left
//若返回途中有右子树,则遍历该右子树,重复操作 public List < Integer > inorderTraversal(TreeNode root) { List < Integer > res = new ArrayList < > (); Stack < TreeNode > stack = new Stack < > (); TreeNode curr = root; while (curr != null || !stack.isEmpty()) { while (curr != null) { stack.push(curr); curr = curr.left; } curr = stack.pop(); res.add(curr.val); curr = curr.right; } return res; }
莫里斯遍历
原理:线索二叉树
实现方法:
1 2 3 4 5 6 7 8
Step 1: 将当前节点current初始化为根节点 Step 2: While current不为空 ①若current没有左子节点 a. 将current添加到输出 b. 进入右子树,亦即, current = current.right ②否则 a. 在current的左子树中,令current成为最右侧节点的右子节点 b. 进入左子树,亦即,current = current.left