剑指offer-面试题 55:二叉树的深度

题目描述:

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

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

样例

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

输出:3

解法一:

/**
 * 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==NULL)
        {
            return 0;
        }
        int left = treeDepth(root->left);
        int right = treeDepth(root->right);
        return max(left, right) + 1;
    }
};

 

猜你喜欢

转载自blog.csdn.net/wchzh2015/article/details/89608338