蓝桥杯 DFS 二叉树最大深度(简单)

问题描述

 

 给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3

   / \

  9  20

    /  \

   15   7

返回它的最大深度 3 。

参考代码

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);
}
}

猜你喜欢

转载自blog.csdn.net/qq_40185047/article/details/114500482
今日推荐