Java解析二叉树结构

时间:2013-08-06 18:02:58

标签: java recursion tree binary-tree

我目前正在浏览一些数据结构,并且我遇到了一些存储在二叉树中的数据,我并不完全确定解析它的最佳方法。

基本上,数据存储如下:

Structure 1: 
  LeftChild: 0xaddress
    Structure 2: 
      LeftChild: 0xaddress
        Structure 3:
         LeftChild: 0xaddress
          ........
         RightChild: 0xaddress
          Structure 4:
            LeftChild: 0xaddress
            RightChild: 0xaddress
      RightChild: 0xaddress
  RightChild: 0xaddress

现在显然很难对二叉树进行文本解释,所以希望我上面的不良尝试能够解释一下。本质上,它始于一个结构,它有一个左右树条目,每个树条目依次左右,最终其中一个将用完节点,然后树的下一个分支继续。

我不完全确定解决这个问题的最佳方法。

我的第一个是通过使用while循环继续追逐树节点,但这似乎有点令人头疼的跟踪。

我知道Java有二叉树实现,但我不知道是否可以将它们用于这种工作。我从来没有尝试过使用它们,所以我可能错了。

如果有人对如何解决这个问题有任何意见或建议,我将不胜感激。

谢谢!

4 个答案:

答案 0 :(得分:2)

一个建议:如果你的树太深,你应该避免基于递归的解决方案。那是因为你可能有堆栈溢出问题。

要处理这种情况,您可以使用堆栈。

以下伪代码遍历所有二叉树节点而不进行递归。

visitNodes(root) 
    add the root on the stack

    while the stack is not empty
        nodeToBeProcessed <- pop the top node from the stack

        process nodeToBeProcessed

        if nodeToBeProcessed has a left child
            add the left child on the stack

        if nodeToBeprocessed has a right child
            add the right child on the stack

注意:pop操作返回并从堆栈中删除顶级节点。

注2:如果深度不是问题,基于递归的解决方案通常更简单。

答案 1 :(得分:1)

递归是以某种伪代码形式执行此操作的传统方式:

Node { // data
    Node leftChild;
    Node rightChild;
}

handleNode(Node node) {
    if (node is missing or null or blank)
        return;
    ... handle anything on the node
    handleNode(node.leftChild);
    handleNode(node.rightChild);
}

答案 2 :(得分:1)

如果我理解正确,你的问题是从具有该格式的文件中读取信息,而不是在解析后遍历树。您应该创建节点并跟踪谁是使用堆栈的兄弟,您可以获得构建节点的方法。

Stack<String> stack = new Stack<String>();
try {
    BufferedReader in = new BufferedReader(new FileReader("yourfile.txt"));
    String str;
    while ((str = in.readLine()) != null)
    {

        if(str.contains("Structure"))
        {
            stack.push(str);
        }else
        {
            if(str.contains("Left"))
            {
                stack.push(str);
            }
            if(str.contains("Right"))
            {
                System.out.println(stack.pop());    
                System.out.println(str);
                System.out.println(stack.pop());
            }
        }
    }
    in.close();
} catch (IOException e) {
    e.printStackTrace();
}

使用您的示例,此代码将打印:

         LeftChild: 0xaddress
         RightChild: 0xaddress
        Structure 3:
            LeftChild: 0xaddress
            RightChild: 0xaddress
          Structure 4:
      LeftChild: 0xaddress
      RightChild: 0xaddress
    Structure 2: 
  LeftChild: 0xaddress
  RightChild: 0xaddress
Structure 1: 

您可以使用它来构建节点。希望它有所帮助。

答案 3 :(得分:0)

我不确定你是如何实现yoru的东西,但试试这个(你需要做一些明显的名称更改):

//list to put all data into
private static ArrayList<String> list = new ArrayList<String>();

//recursive way to search binary tree
public void binaryTreeSearchAndParse(Node root)
{
    //does it exist?
    if(root != null)
    {
        list.add(root.getData());
        binaryTreeSearchAndParse(root.getLeft());
        binaryTreeSearchAndParse(root.getRight());
        //you may or may not need this depending on how you implemented your tree
        //binaryTreeSearchAndParse(root.getNextStructure());
    }    
}

public static void main(String[] args)
{

   //get tree
   //pass in root of tree
   binaryTreeSearchAndParse(tree.getRoot());

    //now all data should be added in the global ArrayList
    for(int i = 0; i<list.size(); i++)
    {
         System.out.println(list.get(i));
    }
}

如果我知道你如何实现你的树,我可以帮助你更多。

这是递归解决方案。如果您需要迭代解决方案,则应使用队列:

Binary search tree level order with parent node

相关问题