111、257(遞歸,DFS)

類別: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));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章