[二叉树专题]求二叉树的高度(深度)

/* 递归解法 O(n)
1。如果二叉树为null,则二叉树的深度为0;
2. 如果二叉树不为null,则二叉树的深度=max(左子树的深度,右子树的深度)+1;
public static int getDepthRec(TreeNode root){
    if(root == null){
        return 0;
    }
    
    int leftDepth = getDepthRec(root.left);
    int rightDepth = getDepthRec(root.right);
    return Math.max(leftDepth,rightDepth)+1;
}
/* 迭代解法O(n)
基本思想同LevelOrderTravelsal,还是用一个Queue。
*/
public static int getDepth(TreeNode root){
    if(root == null){
        return 0;
    }
    
    int depth = 0;//深度
    int currentLevelNodes = 1;//当前level,node的数量
    int nextLevelNodes = 0;//下一层,node的数量
    
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);
    while(!queue.isEmpty()){
        TreeNode cur = queue.remove();//从队头的位置移除
        currentLevelNodes--;//减少当前level node数量
        if(cur.left != null)(    //如果有左孩子,则加到队尾
            queue.add(cur.left);
            nextLevelNodes++;//并增加下一层Level Node 的数量
        )
        if(cur.right != null){//如果有右孩子,加到队尾
            queue.add(cur.right);
            nextLevelNodes++;
        }
        
        if(currentLevelNodes == 0){//已经遍历完当前层的所有节点
            depth ++; //增加高度
            currentLevelNodes = nextLevelNodes;//初始化下一层
            nextLevelNodes = 0;
        }
    }
    return depth;
}


转载于:https://my.oschina.net/u/2477353/blog/662937

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值