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));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值