二叉树的最大深度

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

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

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

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。


/**
 * 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) {
        if(root == null)
        {
            return 0;
        }
        else
        {
            //递归实现,先进入到最深最深的左节点或右节点,然后慢慢加上来
            int left = MaxDepth(root.left);
            int right = MaxDepth(root.right);
            return left > right ? left + 1 : right + 1; 
        }
    }
}


我原本的思路是,用一个List来存储每一层的所有节点,然后取出来遍历(清空list),如果不为空就将他们的子节点添加到list中并将深度加1,直到list中的为空为止。

public class Solution {
    public int MaxDepth(TreeNode root) {
        List<TreeNode> list = new List<TreeNode>();
        list.Add(root);
        
        int height = 0;
        while(list.Count > 0)
        {
            bool isHeight = false;
            TreeNode[] all = list.ToArray();
            list.Clear();
            foreach(TreeNode node in all)
            {
                if(node != null)
                {
                    isHeight = true;
                    list.Add(node.left);
                    list.Add(node.right);
                }
            }
            
            if(isHeight)
            {
                height++;
            }
        }
        
        return height;
    }
}

首页 我的博客
粤ICP备17103704号