Minimum Depth of Binary Tree

来源:互联网 发布:注册淘宝要多少钱 编辑:程序博客网 时间:2024/05/21 08:53

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.

方法一:

从根节点开始计数,直到叶子节点,寻找最短路径.

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int depthCore(TreeNode *root,int depth){        if (!root->left && !root->right) return depth;        int max = (unsigned int)(~0)>>1;        int left = max;        int right = max;                if (root->left)            left = depthCore(root->left,depth+1);        if (root->right)            right = depthCore(root->right,depth+1);                    return left<right? left:right;    }    int minDepth(TreeNode *root) {        if (!root) return 0;        return depthCore(root,1);    }};

方法二:

从叶子节点开始计数,直到根节点,寻找最短路径.

/** * Definition for binary tree * 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) return 0;        int left = minDepth(root->left);        int right = minDepth(root->right);        if (left*right!=0) return min(left,right)+1;        if (left==0) return right+1;        if (right==0) return left+1;    }};

0 0