小目标 To be or not to be

Leetcode 104 Maximum depth of Binary Tree

2017-03-03
chaowyc

Leetcode 104 题

Difficulty:Easy

Tag: Binary Tree

Maximum Depth of Binary Tree

题目原址:https://leetcode.com/problems/maximum-depth-of-binary-tree/?tab=Description

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.

思路

图的遍历算法:

此次采用 中序遍历,也即 DFS 深度优先算法

递归shix

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

Similar Posts

Comments