Leetcode:104. 二叉樹的最大深度
阿新 • • 發佈:2018-11-13
給定一個二叉樹,找出其最大深度。
二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定二叉樹 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
解題思路:
遞迴。從根節點開始訪問,當前深度為1。遞迴查詢左子樹的最大深度depth_left以及右子樹的最大深度depth_right。假設當前層的深度為depth,那麼計算得到的樹的最大深度為depth=depth+max(depth_left,depth_right)。應當注意的是當訪問完左子樹後,注意恢復當前層的初始資料,才能訪問右子樹。演算法的時間複雜度為樹的規模(n)。
#define hasLChild(x) (!(x->left==NULL)) #define hasRChild(x) (!(x->right==NULL)) #define hasChild(x) (hasLChild(x)||hasRChild(x)) class Solution { public: int maxDepth(TreeNode* root) { if (root == NULL) return 0; DFS(root); return depth; } void DFS(TreeNode* root) { if (hasChild(root)) depth++; int l = depth, r = depth, sgn = depth; if (root->left != NULL) { DFS(root->left); l = depth; } if (root->right != NULL) { depth = sgn; DFS(root->right); r = depth; } depth = (l > r ? l : r); } private: int depth = 1; }; |