类别:recursive, DFS
111-Minimum Depth of Binary Tree
题目描述:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
算法分析:
递归实现,对于根节点,如果不为NULL, 则深度加1,分别在此深度的基础上递归左子树和右子树,当左右子树都为NULL的时候,即为最终的深度之一,判断比较当前的深度并去较小值。
代码实现:
class Solution {
public:
int minDepth(TreeNode* root) {
int result = INT_MAX;
int len = 0;
if (root == NULL) result = 0;
else recursiveDepth(result, root, len + 1);
return result;
}
void recursiveDepth(int& result, TreeNode* root, int len) {
if (root->left == NULL && root->right == NULL) {
result = min(result, len);
}
if (root->left != NULL) recursiveDepth(result, root->left, len + 1);
if (root->right != NULL) recursiveDepth(result, root->right, len + 1);
}
};
257-Binary Tree Paths
题目描述:
算法:与111的算法非常相似
代码实现:
// 非常简介巧妙的递归思路
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if (root == NULL) return result;
myBinaryTreePaths(result, TreeNode* root, to_string(root->val));
return result;
}
void myBinaryTreePaths(vector<string>& result, TreeNode* root, string str) {
if (root->left == NULL && root->right == NULL) {
result.push_back(str);
}
if (root->left != NULL) myBinaryTreePaths(result, root->left, str + "->" + to_string(root->left->val));
if (root->right != NULL) myBinaryTreePaths(result, root->right, str + "->" + to_string(root->right->val));
}