二叉树的遍历

- 前序遍历:根结点 →\rightarrow→ 左子树 →\rightarrow→ 右子树
- 中序遍历:左子树 →\rightarrow→ 根结点 →\rightarrow→ 右子树
- 后序遍历:左子树 →\rightarrow→ 右子树 →\rightarrow→ 根结点
前序遍历
代码实现:
/**
* 前序遍历
*/
public void preorder(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
TreeNode pNode = root;
while (pNode != null || !stack.isEmpty()) {
if (pNode != null) {
System.out.print(pNode.value + " ");
stack.push(pNode);
pNode = pNode.left;
} else {
TreeNode node = stack.pop();
pNode = node.right;
}
}
}
中序遍历
代码实现:
/**
* 中序遍历
*/
public void inorder(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
System.out.print(root.value + " ");
root = root.right;
}
}
后序遍历
代码实现:
/**
* 后序遍历
*/
public void postorder(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
root = stack.pop();
if (root != null) {
stack.push(root);
stack.push(null);
if (root.right != null) {
stack.push(root.right);
}
if (root.left != null) {
stack.push(root.left);
}
} else {
TreeNode node = stack.pop();
System.out.print(node.value + " ");
}
}
}
如果本篇文章对你有帮助的话,请点个赞叭~

&spm=1001.2101.3001.5002&articleId=136772542&d=1&t=3&u=7da99319aed34483a6ca38f990c65264)
2182

被折叠的 条评论
为什么被折叠?



