java Iterativel preorder在二叉树中遍历
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Iterativel preorder在二叉树中遍历相关的知识,希望对你有一定的参考价值。
# Preorder traversal: node -> node.left -> node.right
public void preorder(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (stack.size > 0 || current != null) {
if (current != null) {
visit(current);
stack.push(current);
current = current.left;
} else {
current = stack.pop();
current = current.right;
}
}
}
// second implementation
public void preorder2(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode current;
stack.push(root);
while (stack.size() > 0) {
current = stack.pop();
visit(current);
if (current.left != null) stack.push(current.left);
if (current.right != null) stack.push(current.right);
}
}
以上是关于java Iterativel preorder在二叉树中遍历的主要内容,如果未能解决你的问题,请参考以下文章
java 144.二叉树Preorder Traversal(Morris).java
java 144.二叉树Preorder Traversal(Morris).java
java 144.二叉树Preorder Traversal(Morris).java
java 144.二叉树Preorder Traversal(Morris).java
java 144.二叉树Preorder Traversal(Morris).java
java 144.二叉树Preorder Traversal(Morris).java