破解编码面试。 4.1最小深度公式

时间:2015-07-08 23:52:05

标签: c++

在CTCI中,他们给出了二叉树最小深度的公式,我很困惑。这是代码:

    public static int minDepth(TreeNode root) {
        if (root == null) {
           return 0;
        }
        return 1 + Math.min(minDepth(root.left), minDepth(root.right));
    }

最小深度的定义是叶子节点,它是从根目录开始的最短路径吗?如果定义错误,请纠正我。

DILEMMA:我将root用15作为BST。然后继续向树中添加5,7,10,20,25,30,35。然后使用代码输出min为2。 如果我只是添加了10和25,那么min的输出也只是2.这假设是正确的吗?

我在这里将我的代码翻译成C ++,所以请告诉我,如果我在代码中犯了一个错误就搞砸了

     int findMin(Node* root)
     {
         if (root == NULL)
            return 0;

         return 1 + std::min(findMin(root->left), findMin(root->right));
     }

    void addNum(Node*& root, int n)
    {
        if (root == NULL){
            Node* temp = new Node(n);
            root = temp;
            return;
        }

         if (n > root->num){
             addNum(root->right, n);
         }
         else{
             addNum(root->left, n);
         }
     }

非常感谢!

1 个答案:

答案 0 :(得分:0)

  

输入{15,10,20}

输入1:最初,将15添加到BST中

    15

输入2:现在,将10添加到BST中

    15
   /
  10

输入3:现在,将20添加到BST中

    15
   /  \
  10  20

因此 BST minmax高度为2


  

现在,考虑另一个输入案例{15,5,7,10,20,25,30,35}

输入1:最初,将15添加到BST中

    15

输入2:现在,将5添加到BST中

    15
   /
  5

输入3:现在,将7添加到BST中

    15
   /
  5
   \
    7

输入4:现在,将10添加到BST中

    15
   /
  5
   \
    7
     \
      10

输入5:现在,将20添加到BST中

    15
   /  \
  5   20 
   \
    7
     \
      10

输入6:现在,将25添加到BST中

    15
   /  \
  5   20 
   \    \
    7   25
     \
      10

输入7:现在,将30添加到BST中

    15
   /  \
  5   20 
   \    \
    7   25
     \    \
      10   30

输入8:现在,将35添加到BST中

    15
   /  \
  5   20 
   \    \
    7   25
     \    \
      10   30
            \
            35

正如您从上图所见, BST = min&的4 身高 max身高= 5


因此,如果正确查看findMin代码,您会发现错误:

int findMin(Node* root)
 {
     if (root == NULL)
        return 0;

     return 1 + std::min(findMin(root->left), findMin(root->right));
 } 

错误:当您的root指向5时(即第二个示例中为15的左子),它将返回1给它的父母。 (为什么?)

更正:以下代码段将正常运行:

int min_depth(struct Node* root, int depth)
{
    if (root->left == NULL && root->right == NULL)
        return depth;

    int x = (root->left != NULL) ? min_depth(root->left, depth+1) :  depth;
    int y = (root->right != NULL) ? min_depth(root->right, depth+1) : depth;

    return (x < y) ? x : y;
}
相关问题