Home  >  Q&A  >  body text

算法 - 如何不用递归 列出 树(多叉) 中根节点到叶节点的所有路径(Java)

比如,对于下面这个二叉树,它所有的路径为:

8 -> 3 -> 1

8 -> 2 -> 6 -> 4

8 -> 3 -> 6 -> 7

8 -> 10 -> 14 -> 13

怎么用Java去实现?

天蓬老师天蓬老师2743 days ago600

reply all(4)I'll reply

  • 阿神

    阿神2017-04-18 10:53:58

    If you don’t need recursion, then use depth first!
    Use the stack, first push the root node into the stack, if the stack is not empty, then pop it out and output the median value of the current node, then push the right subtree onto the stack first, then push the left subtree onto the stack, and then Determine whether the stack is empty, loop... The steps are as follows:
    1) First push the root node of the binary tree into the stack
    2) Determine whether the stack is empty, if not, pop it out of the stack and output the pop tree The value of the node
    3) The right subtree of the pop tree node is pushed onto the stack
    4) The left subtree of the pop tree node is pushed onto the stack
    5) Loop back to (2)
    This is the one I saw before Method, I wonder if it can help the questioner?

    public void depthOrderTraversal(){  
            if(root==null){  
                System.out.println("empty tree");  
                return;  
            }         
            ArrayDeque<TreeNode> stack=new ArrayDeque<TreeNode>();  
            stack.push(root);         
            while(stack.isEmpty()==false){  
                TreeNode node=stack.pop();  
                System.out.print(node.value+"    ");  
                if(node.right!=null){  
                    stack.push(node.right);  
                }  
                if(node.left!=null){  
                    stack.push(node.left);  
                }             
            }  
            System.out.print("\n");  
        }  

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:53:58

    Replace recursion with stack: https://zh.coursera.org/learn...

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:53:58

    Depth first? . .

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:53:58

    Use breadth-first traversal, then store all the parent nodes of the node in the state, and output them after reaching the leaf node.

    reply
    0
  • Cancelreply