二叉树各路径结点之和并找出最大值的路径:先序遍历

这里写图片描述
如图所见,一个二叉树,各结点值是int类型,现在要找出各结点之和最大的路径。

如图可知,此二叉树有三条路径:

1,2,4],[1,2,5],[1,3]

结点之和最大的是[1,2,5],我们最终的目标就是要找到这条路径!

这里用的是先序遍历
当发现到达叶子结点时,确认一条路径,并将这路径中各结点相加得到sum,然后退回至父结点再次寻找另其它叶子结点,重复之前的操作,并与上次的sum进行比较…

  如此重复下去,直至所有路径都遍历完成,sum保存的就是结点之和最大的值,关键是如何保存sum的路径?

  当然是栈咯… 栈顶叶子结点,栈底根结点,嗯!

public class TreeNode {
    private TreeNode leftNode;
    private int val;
    private TreeNode rightNode;
    }
public class FindPath {
    private static Stack<TreeNode> stack = new Stack<TreeNode>(); //存节点

    private static TreeMap<Integer, String> treeMap = new TreeMap<Integer,String>(); //存储每条路径的和

    public static void findMaxValueOfPath(TreeNode tree){
        if(null == tree) return ;

        stack.push(tree);

        if(tree.getLeftNode() == null && tree.getRightNode() == null){
            String string = " ";
            int sum = 0;
            for(TreeNode tmp : stack){ //拿出有的
                string += tmp.getVal() + "->";
                sum +=tmp.getVal();
            }
            treeMap.put(sum, string);
            stack.pop(); //出栈结束
        }else{
            //左节点与右节点
            findMaxValueOfPath(tree.getLeftNode());

            findMaxValueOfPath(tree.getRightNode());

            stack.pop();
        }

    }
}

猜你喜欢

转载自blog.csdn.net/guo_binglo/article/details/80577971