JZ38 - 二叉树的深度

题目描述

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

  • 递归 JS
/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function TreeDepth(pRoot)
{
    // write code here
    if(pRoot == null){
        return 0;
    }
    var h = 0;
    h = Math.max(TreeDepth(pRoot.left), TreeDepth(pRoot.right)) + 1;
    return h;
}
  • 按层遍历,利用辅助队列,每一层的节点加入,然后再层中遍历,弹出层中节点,加入层中节点的左右子节点,遍历完一层深度加一。 python
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        if pRoot == None:
            return 0
        q = []
        depth = 0
        q.append(pRoot)
        while len(q)>0:
            for i in range(len(q)):
                cur = q.pop(0)
                if cur.left:
                    q.append(cur.left)
                if cur.right:
                    q.append(cur.right)
            depth += 1
        return depth

 

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