二叉树的最大深度

  • maximum depth of binary tree

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

  • 题目大意:给定一棵二叉树,找它的最大深度。最大深度指的是从根节点向下到最远的叶子节点,沿着这条路径走过所经过的节点的数目。

  • 思路:递归左右子树,左右子树最深的子树的高度加一,就是当前二叉树的最大深度。

// Definition for binary tree
struct TreeNode {
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
  public:
    int maxDepth(TreeNode *root) {
      // 需要填入的代码块
      if(root == NULL)return 0;
      int leftLength = maxDepth(root->left);
      int rightLength = maxDepth(root->right);
      return leftLength > rightLength ? (leftLength+1) : (rightLength+1);
      // 需要填入的代码块
    }
  };
  • 测试结果

运行结果

 

posted @ 2018-11-23 23:54  走走停停yyl  阅读(107)  评论(0编辑  收藏  举报