首页 > Windows开发 > 详细

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

时间:2018-11-22 14:59:15      阅读:159      评论:0      收藏:0      [点我收藏+]

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)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!