[LeetCode] Minimum Depth of Binary Tree

来源:互联网 发布:淘宝账号冻结怎么解冻 编辑:程序博客网 时间:2024/06/07 14:56

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.

问题描述:给定一个二叉树,找到它的最小深度。最小深度定义为从根节点到最近的叶子节点的最短路径。

看到这个题,一般人可能会写出下面的代码:

    int minDepth(TreeNode *root)    {        if(root == NULL)            return 0;        int lh = minDepth(root->left);        int rh = minDepth(root->right);        return lh<rh ? lh+1 : rh+1;    }
不过仔细想想,这段代码求的是什么呢?这段代码求的是节点的最低高度。直观的解释是节点的高度是左右孩子节点的深度的最小值,那得到的应该是节点的最小高度值。

本题要求的是根节点到最近的叶子节点的最短路径。那么,就可以用一个变量来跟踪叶子节点的层次,不过当左子树或者右子树为空时,就必须分开讨论了。

class Solution {public:    int minD(TreeNode *root, int lev)    {        if(root == NULL)            return lev;                if(root->left == NULL && root->right == NULL)            return lev;        if(root->left == NULL && root->right)            return minD(root->right, lev + 1);        if(root->left && root->right == NULL)            return minD(root->left, lev + 1);                int lh = minD(root->left, lev + 1);        int rh = minD(root->right, lev + 1);                return lh<rh ? lh : rh;    }        int minDepth(TreeNode *root) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.         if(root == NULL)            return 0;                    return minD(root, 1);    }};

原创粉丝点击