java遍历节点,遍历Java中二叉树的所有节点

Let's say I have a simple binary tree node class, like so:

public class BinaryTreeNode {

public String identifier = "";

public BinaryTreeNode parent = null;

public BinaryTreeNode left = null;

public BinaryTreeNode right = null;

public BinaryTreeNode(BinaryTreeNode parent, String identifier)

{

this.parent = parent; //passing null makes this the root node

this.identifier = identifier;

}

public boolean IsRoot() {

return parent == null;

}

}

How would I add a method which is able to recursively traverse through any size tree, visiting each and every existing node from left to right, without revisiting a node that has already been traversed?

Would this work?:

public void traverseFrom(BinaryTreeNode rootNode)

{

/* insert code dealing with this node here */

if(rootNode.left != null)

rootNode.left.traverseFrom(rootNode.left);

if(rootNode.right != null)

rootNode.traverseFrom(rootNode.right);

}

解决方案

There are 3 types of Binary tree traversal that you can achieve :

example:

consider this following Binary tree :

D3HIJ.png

Pre-order traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)

In-order traversal sequence: A, B, C, D, E, F, G, H ,I (left, root, right)

Post-order traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)

code example:

left to right traversal of the Binary tree, nay In order Traversal of binary tree :

public void traverse (Node root){ // Each child of a tree is a root of its subtree.

if (root.left != null){

traverse (root.left);

}

System.out.println(root.data);

if (root.right != null){

traverse (root.right);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值