Try   HackMD

【LeetCode】 104. Maximum Depth of Binary Tree

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.

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.

Solution

  • 用一個變數代表最深深度,一個變數代表現在深度,跑DFS即可。

Code

/** * 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: void FindDepth(TreeNode* node, int nowdepth,int &depth) { if(!node)return; depth = max(depth,nowdepth); FindDepth(node->left,nowdepth+1,depth); FindDepth(node->right,nowdepth+1,depth); } int maxDepth(TreeNode* root) { int depth=0; FindDepth(root,1,depth); return depth; } };
tags: LeetCode C++