Algorithm to print all paths with a given sum in a binary tree

后端 未结 18 1369
既然无缘
既然无缘 2020-12-24 07:04

The following is an interview question.

You are given a binary tree (not necessarily BST) in which each node contains a value. Design an algorithm t

18条回答
  •  攒了一身酷
    2020-12-24 07:43

    public void printPath(N n) {
        printPath(n,n.parent);
    }
    
    private void printPath(N n, N endN) {
        if (n == null)
            return;
        if (n.left == null && n.right == null) {
            do {
                System.out.print(n.value);
                System.out.print(" ");
            } while ((n = n.parent)!=endN);
            System.out.println("");
            return;
        }
        printPath(n.left, endN);
        printPath(n.right, endN);
    }
    

    You can print tree path end the n node. like this printPath(n);

提交回复
热议问题