二叉樹的最大深度
-
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); // 需要填入的程式碼塊 } };
- 測試結果

測試結果