求二叉树的深度

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

语言java
方法一(非递归)
1.把根节点放入一个队列
2.从队列取出根节点,判断左右子树是否空,不为空推入队列
3.深度+1,同时记录下一层节点的个数
4.判断当前队列个数是否为0,不为0,遍历队列里所有节点,判断左右子树是否空,不为空推入队列,遍历次数达到3记录的节点数,深度+1,同时记录下一层节点的个数
5.为0退出返回二叉树深度

import java.util.Queue;
import java.util.LinkedList;

public class Solution {
    public int TreeDepth(TreeNode root) {
        if (root == null)
            return 0;
        Queue queue = new LinkedList();
        queue.add(root);
        int dep = 0,count = 0,nextCount = 1;
        while(queue.size()!=0)
        {
            TreeNode top = queue.poll();
            count++;
            if(top.left != null){
                queue.add(top.left);
            }
            if(top.right != null){
                queue.add(top.right);
            }
            if(count == nextCount){
                count = 0;
                nextCount = queue.size();
                dep++;
            }
        }
        return dep;
        
    }
}

方法二:递归
1.判断当前节点是否为空,不为空返回左右节点的递归后各自+1的最大值(1表示这一层有数据);

import java.lang.Math;
public class Solution {
    public int TreeDepth(TreeNode pRoot)
    {
        if(pRoot == null){
            return 0;
        }
        int left = TreeDepth(pRoot.left);
        int right = TreeDepth(pRoot.right);
        return Math.max(left, right) + 1;
    }
}

你可能感兴趣的:(求二叉树的深度)