标签:null 声明 imu value style tco minimum solution panel
二叉树的最大深度
解题思路
深度优先搜索,将每一层的深度传给下一层,直到传到叶节点,将深度存入集合。最后取出集合中最大的数即为最大深度。
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public int MaxDepth(TreeNode root) { //若无根节点返回深度为0 if(root==null) return 0; //声明集合保存各个叶节点的深度 List<int> depthList = new List<int>(); //搜索树的深度,传入根节点、集合、根节点深度 Search(root,depthList,1); //获取集合中最大深度 int maxDepth = int.MinValue; foreach(int depth in depthList) if (depth > maxDepth) maxDepth = depth; return maxDepth; } public void Search(TreeNode root, List<int> depthList, int rootDepth){ //如果节点左右子节点都不存在则为叶节点,将其深度存入集合 if (root.left == null&& root.right == null) depthList.Add(rootDepth); //否则,继续递归遍历节点的左右节点,将节点的深度传给其左右子节点 if (root.left != null) Search(root.left, depthList, rootDepth + 1); if (root.right != null) Search(root.right, depthList, rootDepth + 1); } }
二叉树的最小深度
解题思路
与最大深度类似,取出集合中最小的值即可
标签:null 声明 imu value style tco minimum solution panel
原文地址:https://www.cnblogs.com/errornull/p/10001003.html