打印树的最小总和路径

时间:2018-06-18 10:28:55

标签: java tree

我有一个代码,用于计算我创建的树的最小总和路径。

My Tree Class是这样的:

import java.util.LinkedList;
import java.util.Queue;
public class SolutionTree {

    SolutionNode root;

    public SolutionTree() {
        root = null;
    }

    public void addRoot(int rootValue) {
        root = new SolutionNode(rootValue);
    }

    // New Node Adder
    public void addSolutionNode(int newNodeValue) {
        SolutionNode newNode = new SolutionNode(newNodeValue);
        SolutionNode newNodeRoot = breadth(root);
        if(newNodeRoot.getChildLeft() == null) {
            newNodeRoot.setChildLeft(newNode);
            newNode.setParentLeft(newNodeRoot);
        }
        else if(newNodeRoot.getChildRight() == null) {
            newNodeRoot.setChildRight(newNode);
            newNode.setParentLeft(newNodeRoot);
            if(newNodeRoot != root) {
                    if(newNodeRoot.getParentLeft().getChildRight().getChildLeft() == null) {
                        newNodeRoot.getParentLeft().getChildRight().setChildLeft(newNode);
                        newNode.setParentRight(newNodeRoot.getParentLeft().getChildRight());
                    }
            }
        }
    }

    // Node Class of Solution Tree
    protected class SolutionNode {

        private int value;
        private SolutionNode parentLeft;
        private SolutionNode parentRight;
        private SolutionNode childLeft;
        private SolutionNode childRight;

        // Constructor
        public SolutionNode() {
            value = 0;
            parentLeft = null;
            parentRight = null;
            childLeft = null;
            childRight = null;
        }

        // Constructor
        public SolutionNode(int v) {
            value = v;
            parentLeft = null;
            parentRight = null;
            childLeft = null;
            childRight = null;
        }

        // MODIFIERS

        public void setValue(int val) {
            value = val;
        }

        public void setParentLeft(SolutionNode leftParent) {
            parentLeft = leftParent;
        }

    public void setParentRight(SolutionNode rightParent) {
        parentLeft = rightParent;
    }

        public void setChildLeft(SolutionNode leftChild) {
            childLeft = leftChild;
        }

        public void setChildRight(SolutionNode rightChild) {
            childRight = rightChild;
        }

        //ACCESSORS

        public int getValue() {
            return value;
        }

        public SolutionNode getParentLeft() {
            return parentLeft;
        }

        public SolutionNode getParentRight() {
            return parentRight;
        }

        public SolutionNode getChildLeft() {
            return childLeft;
        }

        public SolutionNode getChildRight() {
            return childRight;
        }




    }

    // function to compute the minimum sum path
    // It only returns the sum of the values of nodes on the min sum path 
    int minSumPath(SolutionNode current) {
        if(current == null)
            return 0;

        int sum = current.getValue();

        int left_sum = minSumPath(current.childLeft);
        int right_sum = minSumPath(current.childRight);

        if(left_sum <= right_sum) {
            sum += minSumPath(current.childLeft);
        }
        else {
            sum += minSumPath(current.childRight);
        }

        return sum;
    }

    // Breadth First Traversal
    public static SolutionNode breadth(SolutionNode root) {
        Queue<SolutionNode> queue = new LinkedList<SolutionNode>() ;
        if (root == null)
            return null;
        queue.clear();
        queue.add(root);
       while(!queue.isEmpty()){
            SolutionNode node = queue.remove();
            if(node.childLeft != null) 
                queue.add(node.childLeft);
            if(node.childRight != null) 
                queue.add(node.childRight);
            if(node.childLeft == null || node.childRight == null)
                return node;
        }
        return null;
    }


}

我有一个程序从.txt文件读取整数并添加到解决方案树并计算树的最小总和路径(从根节点到叶节点(节点的valeus的总和))。通过调用SolutionTree的minSumPath方法。

我想打印计算出的路径。如果树是:

,则为例如
        1
    2        3
4        5        6   

最小和路径是7,它是通过求和1 + 2 + 4来计算的。我想打印这个过程。任何想法我怎么能这样做?我将不胜感激任何帮助。

提前致谢。

2 个答案:

答案 0 :(得分:2)

除了在递归方法中返回一个int之外,你应该返回一个保存sum和你传递的节点的String的类。

此代码适用于您:

 public class number{
    private int sum;
    private String str;

    // CONSTRUCTOR
    public number(int sum, String str){
        this.sum=sum;
        this.str=str;
    }

    public void add(int sum2){
        sum+=sum2;
        if(!str.equals(""))
            str = str +" + "+ sum2;
        else if(str.equals(""))
            str = "" + sum2;
    }

    // ACCESSORS
    public String getStr() {
        return this.str;
    }

    public int getSum() {
        return this.sum;
    }

    // MODIFIERS
    public void setStr(String newStr) {
        this.str = newStr;
    }

    public void setSum(int newSum) {
        this.sum = newSum;
    }

}
// function to compute the minimum sum path
// It only returns the sum of the values of nodes on the min sum path 
number minSumPath(SolutionNode current) {
  number  tr1= new number(0,"");
    if(current == null){
        return tr1;
    }
    int sum = current.getValue();

    int left_sum = minSumPath(current.childLeft).sum;
    int right_sum = minSumPath(current.childRight).sum;

    if(left_sum <= right_sum) {
       tr1= minSumPath(current.childLeft);
        tr1.add(sum);
    }
    else {
        tr1= minSumPath(current.childLeft);
        tr1.add(sum);
       }
    return tr1;
}

答案 1 :(得分:1)

为什么不让你创造一个BalancedSearchTree,最小的总和将始终向左,如果失败,向右,那么你所要做的就是遍历树,直到你到达终点。这样您就不必访问树上的所有节点。

这样的事情:

private int minPath(Node<E> n, int min, ArrayList<Integer> pathTaken) {
    if (n.left != null) {// Left is smaller than parent and exists, go there
        pathTaken.add(n.value);
        return minPath(n.left, min + n.value);
    }
    else if (n.right != null) {// Else go right
        pathTaken.add(n.value);
        return minPath(n.right, min + n.value);
    }
    return min; // There are no more children 
}

public minSumPath() {
    if (root == null)
        return -1;
    ArrayList<Integer> pathTaken = new ArrayList<>();
    pathTaken.add(root.getValue());
    int min = minSumPath(root, pathTaken);
    System.out.println("Patk taken: " + pathTaken.toString());
    return min;
}

要保留所采用路径的记录,只需将一个ArrayList添加到递归方法参数中即可。请注意,我没有检查添加的路径是否为空,您可能应该这样做。

private int minSumPath(SolutionNode current, ArrayList<Integer> pathTaken) {
        if(current == null)
            return 0;

        int sum = current.getValue();

        int left_sum = minSumPath(current.childLeft);
        int right_sum = minSumPath(current.childRight);

        if(left_sum <= right_sum) {
            pathTaken.add(current.childLeft.getValue());
            sum += minSumPath(current.childLeft);
        }
        else {
            pathTaken.add(current.childRight.getValue());
            sum += minSumPath(current.childRight);
        }

        return sum;
    }

public minSumPath() {
    if (root == null)
        return -1;
    ArrayList<Integer> pathTaken = new ArrayList<>();
    pathTaken.add(root.getValue());
    int min = minSumPath(root, pathTaken);
    System.out.println("Patk taken: " + pathTaken.toString());
    return min;
}

您可以执行的优化是存储找到的最新最小路径的变量,并且当它所在的路径大于前一个记录时,您返回Integer.MAX_VALUE并中止该分支的递归,因为它在那里找不到更短的路径。