java遍历节点_二叉树的节点遍历

1、节点类

public class Node {

private int data;

private Node left;

private Node right;

public Node(int data) {

this.data = data;

}

public int getData() {

return data;

}

public void setData(int data) {

this.data = data;

}

public Node getLeft() {

return left;

}

public void setLeft(Node left) {

this.left = left;

}

public Node getRight() {

return right;

}

public void setRight(Node right) {

this.right = right;

}

}

2、算法实现类(递归实现)

public class FindTree {

private void visit(int data) {

System.out.print(data+"--");

}

//前序遍历

public void preOrder(Node root) {

if(root == null) {

return;

}

visit(root.getData());

preOrder(root.getLeft());

preOrder(root.getRight());

}

//中序遍历

public void inOrder(Node root) {

if(root == null) {

return;

}

inOrder(root.getLeft());

visit(root.getData());

inOrder(root.getRight());

}

//后续遍历

public void afterOrder(Node root) {

if(root == null) {

return;

}

afterOrder(root.getLeft());

afterOrder(root.getRight());

visit(root.getData());

}

}

3、算法实现类(非递归)

public class FindTree2 {

//先序遍历非递归算法

private void preOrder(Node root) {

if(root!=null) {

Stack stack = new Stack();

for (Node node = root; !stack.empty() || node != null;) {

//当遍历至节点位空的时候出栈

if(node == null) {

node = stack.pop();

}

node.visit();

//遍历右孩子存入栈内

if(node.getRightChild()!=null) {

stack.push(node.getRightChild());

}

//遍历左子树节点

node = node.getLeftChild();

}

}

}

//中序遍历的非递归算法

public void inOrder(Node root) {

if(root!=null) {

Stack stack = new Stack();

for (BinaryTree node = root; !stack.empty() || node != null; ) {

//寻找最左的左子树节点,并将遍历的左节点进栈

while(node!=null) {

stack.push(node);

node = node.getLeftChild();

}

if(!stack.empty()) {

node = stack.pop();      //出栈

node.visit();            //读取节点值

node = node.getRightChild();

}

}

}

}

//后序遍历非递归算法

private void postOrder(Node root) {

if(root!=null) {

Stack stack = new Stack();

for (Node node = root; !stack.empty() || node != null;) {

while(root!=null) {

stack.push(root);

root = root.getLeftChild();

}

while(!stack.empty() && root == stack.peek().getRightChild()) {

root = stack.pop();

root.visit();

}

if (stack.empty()) {

return;

} else {

root = stack.peek().getRightChild();

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值