java中关于树的代码 java树形( 四 )


System.out.println(currentDepth+":"+child);
}
if ( parent._childList.size() != 0 )System.out.println(""+null);// 为了避免叶子节点也会打印null
//打印 parent 同层的节点的孩子
if ( parent._parent != null ){ // 不是root
int i = 1;
while ( iparent._parent._childList.size() ){// parent 的父亲还有孩子
TreeNode current = (TreeNode)parent._parent._childList.get(i);
printSteps( current, currentDepth );
i++;
}
}
// 递归调用,打印所有节点
for ( int i = 0; iparent._childList.size(); i++ ){
TreeNode child = (TreeNode)parent._childList.get(i);
printSteps( child, currentDepth+1 );
}
}
// 按宽度优先遍历 , 打印出parent子树所有的节点
public void printSteps(){
System.out.println(""+_root);
System.out.println(""+null);
printSteps(_root, 1 );
}**/
// 将给定的值做为 parent 的孩子,构建节点
private TreeNode createChildNode( TreeNode parent, Object value ){
TreeNode child = new TreeNode( value , parent );
parent._childList.add( child );
return child;
}
public static void main(String[] args) {
Tree tree = new Tree( new Object[]{ "root", null,
"left", "right", null,
"l1","l2","l3", "|", "r1","r2",null } );
//tree.printSteps();
System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(0) )._childList.get(0) );
System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(0) )._childList.get(1) );
System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(0) )._childList.get(2) );
System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(1) )._childList.get(0) );
System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(1) )._childList.get(1) );
}
}
java:二叉树添加和查询方法
package arrays.myArray;
public class BinaryTree {
private Node root;
// 添加数据
public void add(int data) {
// 递归调用
if (null == root)
root = new Node(data, null, null);
else
addTree(root, data);
}
private void addTree(Node rootNode, int data) {
// 添加到左边
if (rootNode.datadata) {
if (rootNode.left == null)
rootNode.left = new Node(data, null, null);
else
addTree(rootNode.left, data);
} else {
// 添加到右边
if (rootNode.right == null)
rootNode.right = new Node(data, null, null);
else
addTree(rootNode.right, data);
}
}
// 查询数据
public void show() {
showTree(root);
}
private void showTree(Node node) {
if (node.left != null) {
showTree(node.left);
}
System.out.println(node.data);
if (node.right != null) {
showTree(node.right);
}
}
}
class Node {
int data;
Node left;
Node right;
public Node(int data, Node left, Node right) {
this.data = https://www.04ip.com/post/data;
this.left = left;
this.right = right;
}
}
JAVA数据结构关于查找树的节点的代码分析你好,递归调用简单的说就是自己无限的调用自己的下一级,也就是说父节点和子节点拥有相同的属性和方法 , 所以在处理玩当前节点也就是父节点的时候,就调用处理自身下面的子节点,类似于文件夹和文件,文件夹相对于当前目录来说是父节点,而他里面的子文件夹就相当于子节点 , 但是处理子文件夹的时候,子文件夹就成了父节点,一次递归处理完毕
希望可以帮助到你
java中关于树的代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java树形、java中关于树的代码的信息别忘了在本站进行查找喔 。

推荐阅读