來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。
題目描述node
給定一個二叉樹,找出其最小深度。網絡
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。post
說明: 葉子節點是指沒有子節點的節點。code
示例blog
輸入:[3,9,20,null,null,15,7] 輸出:2
題目要求遞歸
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int minDepth(struct TreeNode* root){ }
題解leetcode
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int dfs(int d,struct TreeNode* r){ if(r->left==NULL&&r->right==NULL)return d+1; if(r->left==NULL)return dfs(d+1,r->right); if(r->right==NULL)return dfs(d+1,r->left); return fmin(dfs(d+1,r->left),dfs(d+1,r->right)); } int minDepth(struct TreeNode* root){ if(root==NULL)return 0; if(root->left==NULL&&root->right==NULL)return 1; if(root->left==NULL)return dfs(1,root->right); if(root->right==NULL)return dfs(1,root->left); return fmin(dfs(1,root->left),dfs(1,root->right)); }
搜索到葉子節點時返回深度get
當前節點的左右子節點之一爲空時遞歸非空子節點it
當前節點的左右節點都不爲空時遞歸兩子節點取其最小值io
來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。