Leetcode-111: Minimum Depth of Binary Tree

Solution 1: Recursion. Note that the binary tree degenerates into a singly linked list.

#include <iostream>
#include <algorithm>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int minDepth(TreeNode* root) {
    if (!root) return 0;
    if (root && !root->left && !root->right) return 1;
    if (root && !root->left) return minDepth(root->right)+1;
    if (root && !root->right) return minDepth(root->left)+1;
    return min(minDepth(root->left), minDepth(root->right))+1;

}

int main()
{
    TreeNode t1(3);
    TreeNode t2(9);
    TreeNode t3(20);
    TreeNode t4(15);
    TreeNode t5(7);

    t1.left=&t2;
    t1.right=&t3;
    t3.left=&t4;
    t3.right=&t5;

    cout<<minDepth(&t1)<<endl;

    TreeNode ta(1);
    TreeNode tb(2);
    TreeNode tc(3);
    TreeNode td(4);
    TreeNode te(5);

    ta.left=&tb;
    tb.left=&tc;
    tc.left=&td;
    td.left=&te;

    cout<<minDepth(&ta)<<endl;

    return 0;
}

Solution 2: To be determined

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324962511&siteId=291194637