AcWing 71. 二叉树的深度

题目描述

输入一棵二叉树的根结点,求该树的深度。

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

样例

输入:二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]如下图所示:
    8
   / \
  12  2
     / \
    6   4

输出:3

问题分析 

二叉树的高度等于其根节点的左孩子为根节点的树的高度和其右孩子为根节点的树的高度的较大者加1,当节点为空时,返回其高度为0。最后返回整棵树的高度。

代码实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int treeDepth(TreeNode* root) {
        if(!root)
            return NULL;
        return max(treeDepth(root->left), treeDepth(root->right)) + 1;
    }
};

猜你喜欢

转载自blog.csdn.net/mengyujia1234/article/details/90056700