二叉树的深度

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

题目描述

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


思路:
采用深度优先遍历的方式,获取左子树、右子树的深度,比较下,取大的,再加1就是整个二叉树的深度,这里采用递归和非递归两种方式来做

递归:

  • 终止条件:该节点无左右子树,即为叶子结点时,返回1
  • 不为空,则遍历左右子树,并比较左右子树的深度,取最大的深度+1(加1,代表根节点)返回
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot == NULL)
            return 0;
        if(!pRoot->left&& !pRoot->right)
            return 1;
        else
        {
            int ldepth = TreeDepth(pRoot->left);
            int rdepth = TreeDepth(pRoot->right);
            return 1+(ldepth > rdepth?ldepth:rdepth);
        }
    }
};

非递归方式,借助队列;

  • 每遍历一层,深度加1;
  • 每一层需要一个变量len来记录该层的结点数,也就是队列的当前长度,然后依次在队列中访问该层的len个结点(将队列中的len个元素出队列),并将下一层入队列
/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot==NULL)
            return 0;
        queue<TreeNode*> nodeQueue;
        nodeQueue.push(pRoot);
        int level  = 0;
        while(!nodeQueue.empty())
        {
            int len = nodeQueue.size();
            level++;
            while(len--)
            {
                TreeNode* temp = nodeQueue.front();
                nodeQueue.pop();
                if(temp->left)
                    nodeQueue.push(temp->left);
                if(temp->right)
                    nodeQueue.push(temp->right);
                
            }
        }
        return level;
    }
};
原文地址:https://www.cnblogs.com/whiteBear/p/12608831.html