Blue Bridge Cup DFS Binary Tree Maximum Depth (Simple)

Problem Description

 

 Given a binary tree, find its maximum depth.

The depth of the binary tree is the number of nodes on the longest path from the root node to the farthest leaf node.

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

Example:

Given a binary tree [3,9,20,null,null,15,7],

    3

   / \

  9  20

    /  \

   15   7

Return its maximum depth 3.

Reference Code

import java.util.Stack;

public class Main {
public static void main(String[] args) {
	int [][]aa = {
			{0,1,1,0,0,0,0},
			{1,0,0,0,0,0,0},
			{1,0,0,0,0,1,1},
			{0,0,0,0,0,0,0},
			{0,0,0,0,0,0,0},
			{0,0,1,0,0,0,0},
			{0,0,1,0,0,0,0},
	};
	String[]nodes = {"3","9","20","null","null","15","7"};
	Stack<Integer>sta = new Stack<Integer>();
	boolean [] check = new boolean[nodes.length];
	int max = 0;
	sta.push(0);
	check[0] = true;
	while (!sta.isEmpty()) {
		int temp = sta.peek();
		boolean flag = true;
		for (int i = 0; i < check.length; i++) {
			if (!check[i]&&aa[temp][i] == 1) {
				sta.push(i);
				flag = false;
				check[i] = true;
				break;
			}
		}
		if (flag) {
			if (max<sta.size()) {
				max = sta.size();
			}
			sta.pop();
		}
	}
	System.out.println(max);
}
}

 

Guess you like

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