題目描述:
輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。
實現如下:
//這代碼真沒有什麼要說的。。。
//本題就是樹的遍歷的應用
//最長路徑的長度爲樹的深度,所以當節點的左子樹深度和右子樹深度中的最大值求得後,加1即就是此節點的深度
class Solution
{
public:
int TreeDepth(TreeNode* pRoot)
{
if (pRoot == NULL) return 0;//防禦性動作
int leftChildDepth = TreeDepth(pRoot->left);//求左子樹深度
int rightChildDepth = TreeDepth(pRoot->right);//求右子樹深度
//求當前節點的深度
return (leftChildDepth > rightChildDepth) ? (leftChildDepth + 1) : (rightChildDepth + 1);
}
};