剑指offer_编程题_二叉树的深度

  • 题目
    输入一棵二叉树,求该树的深度。
    从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,
    最长路径的长度为树的深度。
    
  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;
            }
            return TreeDepth(pRoot->left)>TreeDepth(pRoot->right)?TreeDepth(pRoot->left)+1:TreeDepth(pRoot->right)+1;
        }
    };
    
  2. 非递归,层次遍历
    /*
    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;
            }
            std::queue<TreeNode*> q;
            int length, high=0;
            q.push(pRoot);
            length = q.size();
            while(length!=0){
         	   for (int i = 0; i < length; ++i)
         	   {
         		   TreeNode* temp = q.front();
         		   q.pop();
         		   if (temp->left!=NULL) q.push(temp->left);
         		   if (temp->right!=NULL) q.push(temp->right);
         	   }
         	   high += 1;
         	   length = q.size();
            }
            return high;
        }
    };
    
发布了80 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/C_abua/article/details/105704486