Minimum/Maximum Depth of Binary Tree
方法一:基于递归的方式
/** * 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 minDepth(TreeNode* root) { if(root == nullptr) return 0; int lt = minDepth(root->left); int rt = minDepth(root->right); if(lt == 0 && rt == 0) return 1; if(lt == 0) lt = INT_MAX; if(rt == 0) rt = INT_MAX; return 1 + min(lt, rt); } };
方法二:使用递归的方式
/** * 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 minDepth(TreeNode* root) { if(root == nullptr) return 0; stack<pair<TreeNode *, int>> s; s.push(make_pair(root, 0)); int minDep = INT_MAX; while(!s.empty()) { pair<TreeNode *, int> node = s.top(); s.pop(); ++node.second; if(node.first->left == nullptr && node.first->right == nullptr && node.second < minDep) minDep = node.second; if(node.first->left != nullptr) s.push(make_pair(node.first->left, node.second)); if(node.first->right != nullptr) s.push(make_pair(node.first->right, node.second)); } return minDep; } };
Maximum depth of binary tree方法和minimum相同
方法一:递归
/** * 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 == nullptr) return 0; int lt = maxDepth(root->left); int rt = maxDepth(root->right); if(lt == 0 && rt == 0) return 1; if(lt == 0) lt = INT_MIN; if(rt == 0) rt = INT_MIN; return max(lt, rt) + 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 == nullptr) return 0; stack<pair<TreeNode *, int>> s; s.push(make_pair(root, 0)); int maxDep = INT_MIN; while(!s.empty()) { pair<TreeNode *, int> node = s.top(); s.pop(); ++node.second; if(node.first->left == nullptr && node.first->right == nullptr && node.second > maxDep) maxDep = node.second; if(node.first->left != nullptr) s.push(make_pair(node.first->left, node.second)); if(node.first->right != nullptr) s.push(make_pair(node.first->right, node.second)); } return maxDep; } };
 
                    
                
 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号