1. 程式人生 > >LeetCode(42) Maximum Depth of Binary Tree

LeetCode(42) 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.

題目要求計算一棵二叉樹的高度。本題最簡單的解法是遞迴計算左右子樹的高度,並在左右子樹高度的最大值的基礎上加1,則得到本層到葉子節點的高度。

解題程式碼

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