码迷,mamicode.com
首页 > Windows程序 > 详细

LeetCode-C#实现-二叉树(#104/111)

时间:2018-11-22 15:20:57      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:null   声明   imu   value   style   tco   minimum   solution   panel   

104. Maximum Depth of Binary Tree

二叉树的最大深度

解题思路

深度优先搜索,将每一层的深度传给下一层,直到传到叶节点,将深度存入集合。最后取出集合中最大的数即为最大深度。

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

111. Minimum Depth of Binary Tree

二叉树的最小深度

解题思路

与最大深度类似,取出集合中最小的值即可

 

LeetCode-C#实现-二叉树(#104/111)

标签:null   声明   imu   value   style   tco   minimum   solution   panel   

原文地址:https://www.cnblogs.com/errornull/p/10001003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!