Blue Bridge Cup DFS Find the sum of numbers from root to leaf node (medium)

Problem Description

Given a binary tree, each node of it stores a number from 0-9, and each path from the root to the leaf node represents a number.

For example, the path 1->2->3 from the root to the leaf node represents the number 123.

Calculate the sum of all the numbers generated from the root to the leaf nodes.

Explanation: A leaf node refers to a node without child nodes.

Example 1:

Input: [1,2,3]

    1

   / \

  2  3

Output: 25

Explanation:

The path from the root to the leaf node 1->2 represents the number 12.

The path from the root to the leaf node 1->3 represents the number 13.

Therefore, the sum of the numbers = 12 + 13 = 25.

 

Example 2:

Input: [4,9,0,5,1]

    4

   / \

  9  0

 / \

5  1

Output: 1026

Explanation:

The path from the root to the leaf node 4->9->5 represents the number 495.

The path from the root to the leaf node 4->9->1 represents the number 491.

The path from the root to the leaf node 4->0 represents the number 40.

Therefore, the sum of the numbers = 495 + 491 + 40 = 1026.

Reference Code

import java.util.Stack;

public class Main {
public static void main(String[] args) {
	int[][]aa = {
			{0,1,1,0,0},	
			{1,0,0,1,1},	
			{1,0,0,0,0},	
			{0,1,0,0,0},	
			{0,1,0,0,0},	
	};
	int[] nodes = {4,9,0,5,1};
	Stack<Integer> sta = new Stack<Integer>();
	boolean [] check = new boolean[nodes.length];
	int sum = 0;//求和
	sta.push(0);//加入第一个位置定义4为起始点
	check[0] = true;//标记节点4被访问过
	boolean hasNext = false;//判断在撤回的时候的值有没有下一个数
	while (!sta.isEmpty()) {//判断栈非空
		int index = sta.peek();//弹出不删除
		boolean flag = true;//开关
		for (int i = 0; i < check.length; i++) {
			if (!check[i]&&aa[index][i]==1) {
				sta.push(i);
				check[i] = true;//标记被访问过
				flag = false;//改变开关状态
				hasNext = true;
				break;//跳出
			}
		}
		if (flag) {
			if (hasNext) {//这条线路到达尽头sum值加上叶子节点数字值
				int temp = 0;
				for (int i = 0; i < sta.size(); i++) {
					temp = temp*10+nodes[sta.get(i)];
				}
				sum+=temp;
				System.out.println(sta);
			}
			hasNext = false;
			sta.pop();
		}
	}
	System.out.println(sum);
}
}

 

Guess you like

Origin blog.csdn.net/qq_40185047/article/details/114500606