在java中遍历非二叉树
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19338009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
traversing a non binary tree in java
提问by user2277918
I have a tree which is not a binary tree and each node has more that 2 children, I am looking for an algorithm traverse the tree, I am really new in learning data structure, I know how to traverse a binary tree but I get lost when it comes to traverse a non-binary tree . Could any one gives me a hint ?
我有一棵不是二叉树的树,每个节点有两个以上的孩子,我正在寻找一种遍历树的算法,我在学习数据结构方面真的很新,我知道如何遍历二叉树,但我迷路了当涉及到遍历非二叉树时。任何人都可以给我一个提示吗?
回答by Little Child
In a non-binary tree, there will be a Vector
or some other structure that has references to all the children. Make a recursive method as so:
在非二叉树中,将有一个Vector
或一些其他结构引用所有子树。制作一个递归方法,如下所示:
public void traverse(Node child){ // post order traversal
for(Node each : child.getChildren()){
traverse(each);
}
this.printData();
}
Something along those lines.
沿着这些路线的东西。
回答by Joseph
You'll need to use recursion since you can't determine how many children are at each node (breadth) or how far the tree goes (depth). Depending on how you want to traverse, you can use Breadth-first-searchor Depth-first-search.
您将需要使用递归,因为您无法确定每个节点有多少个子节点(宽度)或树走多远(深度)。根据您想要的遍历方式,您可以使用 Breadth-first-search或Depth-first-search。
There is a ton of information on this topic, so give it an attempt to implement one of these recursive methods and please come back if you have trouble along the way!
关于这个主题有大量信息,所以尝试实现这些递归方法之一,如果一路上遇到问题,请回来!
回答by Tarik
Well, when traversing a binary tree, in preorder, you visit the parent node, then recursively traverse the left subtree then recursively traverse the right subtree. With a tree with more than two children, you recursively traverse the subtrees headed by each children. You would do the recursive calls in a for loop.
好吧,当遍历二叉树时,先访问父节点,然后递归遍历左子树,然后递归遍历右子树。对于具有两个以上孩子的树,您可以递归遍历每个孩子所领导的子树。您将在 for 循环中进行递归调用。
回答by Cratylus
The algorithm for pre-post order is the same as a binary tree.
There is no such thing as in-order traversal for a general tree i.e. does not make sense (unless youdefine some order)
pre-post order 的算法与二叉树相同。
没有一般树的有序遍历这样的东西,即没有意义(除非你定义了一些顺序)