题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
/*
public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode (int x)
    {
        val = x;
    }
}*/

分析:求解树的深度有两种算法,一种是递归算法,另一种是非递归算法
递归思路:如果结点为空,返回0;否则遍历其左子树和右子树,返回其左右子树中深度的较大值并加上根结点,即为所求深度
class Solution
{
    public int TreeDepth(TreeNode pRoot)
    {
        if(pRoot!=null)
        {
            int leftHeight=TreeDepth(pRoot.left);
            int rightHeight=TreeDepth(pRoot.right);
            return leftHeight>rightHeight?leftHeight+1:rightHeight+1;
        }
        else
            return 0;
    }
}
非递归思路:层次遍历的思想,若根结点为空,返回0;否则将根结点入队,此时深度为0,当队列不为空时,用一个变量来记录当前队列中结点个数(即该层结点个数),同时深度加1,接着对该层结点遍历,依次从队列中取出结点,遍历其左右子结点,若不为空加入队列,直到所有结点遍历结束,返回深度。
using System.Collections.Generic;
class Solution
{
    public int TreeDepth(TreeNode pRoot)
    {
        Queue<TreeNode> q=new Queue<TreeNode>();
        if(pRoot==null) return 0;
        q.Enqueue(pRoot);
        int depth=0;
        while(q.Count!=0){
            int cnt=q.Count;
            depth++;
            while(cnt--!=0){
                TreeNode tem=q.Peek();
                q.Dequeue();
                if(tem.left!=null) q.Enqueue(tem.left);
                if(tem.right!=null) q.Enqueue(tem.right);
            }
        }
        return depth;
    }
}
复习回顾知识点:
C#队列(Queue)代表了一个先进先出的对象集合。当您需要对各项进行先进先出的访问时,则使用队列。当您在列表中添加一项,称为入队,当您从列表中移除一项时,称为出队
属性:Count属性返回队列中元素个数。
方法:
Enqueue()方法在队列一端添加一个元素。

Dequeue()方法在队列的头部读取和删除元素。如果在调用Dequeue()方法时,队列中不再有元素,就抛出一个InvalidOperationException类型的异常。

Peek()方法从队列的头部读取一个元素,但不删除它。

TrimExcess()方法重新设置队列的容量。Dequeue()方法从队列中删除元素,但它不会重新设置队列的容量。要从队列的头部去除空元素,应使用TrimExcess()方法。

Clear()方法从队列中移除所有的元素。
ToArray()复制队列到一个新的数组中。