[sword finger Offer] - the path obtained by neutralizing a binary tree

Title Description

Input a binary tree and an integer, and print out all paths in which the sum of node values in the binary tree is the input integer. Path is defined as a path from the root node of the tree to the node that the leaf node passes through.
For example, in the following figure, if the binary tree and integer 22 are entered, two paths will be printed, the first path contains nodes 10 and 12, and the second path contains nodes 10, 5 and 7.

There is a fallback to traverse another node, so consider using stacks to store elements.

Solving problems

  • When traversing to a node, stack the current node, and currentSum+=root.node_value.
  • If the current node has no children and currentSum is equal to the target value, the stack element traversal pops up.
  • Otherwise, recursively stack left and right subtrees to continue calling.
Algorithm diagram

Reference code:
package offer;

import java.util.Stack;

 * Neutralization of a binary tree to a path of value
public class Offer34 {
    public static void main(String[] args) {
        BinaryTreeNode root = new BinaryTreeNode(10);
        BinaryTreeNode node1 = new BinaryTreeNode(5);
        BinaryTreeNode node2 = new BinaryTreeNode(12);
        BinaryTreeNode node3 = new BinaryTreeNode(4);
        BinaryTreeNode node4 = new BinaryTreeNode(7);
        root.leftTree = node1;
        root.rightTree = node2;
        node1.leftTree = node3;
        node1.rightTree = node4;
        int target = 22;
        Stack<Integer> path=new Stack<Integer>();
        findPath(root, target,path, 0);

    private static void findPath(BinaryTreeNode root, int target, Stack<Integer> path, int currentSum) {
        boolean isLeaf=root.leftTree==null&&root.rightTree==null;
           while (!path.isEmpty()){
               Integer poll = path.pop();
               System.out.println(poll+" ");



The source code of this question is in my Github Above!

Tags: Java github

Posted on Sun, 10 Nov 2019 12:48:15 -0500 by michaelkirby