欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

104.Maximum Depth of Binary Tree

程序员文章站 2022-05-18 19:36:52
...

problems:
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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.
tips:
求二叉树的最大深度。对于每个根节点,求得它左子树和右子树的最大深度然后加1即可。
solution:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int i,j;
        if(root == NULL) return 0;
        i = maxDepth(root->left)+1;
        j = maxDepth(root->right)+1;
        if(i>=j) return i;
        else return j;
    }
};
相关标签: tree