剑指offer:二叉树中和为某一值的所有路径(java)

暴力方法:遍历所有路径,比较路径和是否为K
优化:子路径结点和大于K时则停止遍历此结点下所有路径

package com.xjb.tree;

import java.util.Stack;

/**
 * @author: xjb
 * @date: 2020/6/5
 * @description: 二叉树中和为某一值的所有路径
 *          1
 *       2      3
 *     4   5   6  7
 *   8   3
 **/
public class PathK {
     

    public static void main(String[] args) {
     
        BinaryTreeNode treeNode1 = new BinaryTreeNode(1);
        BinaryTreeNode treeNode2 = new BinaryTreeNode(2);
        BinaryTreeNode treeNode3 = new BinaryTreeNode(10);
        BinaryTreeNode treeNode4 = new BinaryTreeNode(4);
        BinaryTreeNode treeNode5 = new BinaryTreeNode(5);
        BinaryTreeNode treeNode6 = new BinaryTreeNode(6);
        BinaryTreeNode treeNode7 = new BinaryTreeNode(7);
        BinaryTreeNode treeNode8 = new BinaryTreeNode(8);
        BinaryTreeNode treeNode32 = new BinaryTreeNode(3);
        treeNode1.leftNode = treeNode2;
        treeNode1.rightNode = treeNode3;
        treeNode2.leftNode = treeNode4;
        treeNode2.rightNode = treeNode5;
        treeNode3.leftNode = treeNode6;
        treeNode3.rightNode = treeNode7;
        treeNode4.leftNode = treeNode8;
        treeNode4.rightNode = treeNode32;

        findPath(treeNode1, 10);

    }

    static class BinaryTreeNode {
     
        int value;
        BinaryTreeNode leftNode;
        BinaryTreeNode rightNode;

        public BinaryTreeNode(int value) {
     
            this.value = value;
        }
    }

    public static void findPath(BinaryTreeNode root, int k) {
     
        if (root == null)
            return;
        Stack<Integer> stack = new Stack<Integer>();
        findPath(root, k, stack);
    }

    public static void findPath(BinaryTreeNode root, int k, Stack<Integer> path) {
     
        if (root == null)
            return;
        if (root.leftNode == null && root.rightNode == null) {
     
            if (root.value == k) {
     
                System.out.println("路径开始");
                for (int i : path)
                    System.out.print(i + ",");
                System.out.println(root.value);
            }

        } else {
     
        	//子路径结点和大于K时则停止遍历此结点下所有路径
            if (root.value > k) {
     
                return;
            }
            path.push(root.value);
            findPath(root.leftNode, k - root.value, path);
            findPath(root.rightNode, k - root.value, path);
            path.pop();
        }
    }

}

你可能感兴趣的:(java,java,算法)