2016.6.26——Maximum Depth of Binary Tree

Maximum Depth of Binary Tree

本题收获

1.树时使用递归

2.注意边界条件时输出的值,仔细阅读题意,若是面试时,问清边界条件。

  题目:  

  Given a binary tree, find its maximum depth.

  The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

  题目中说:最短路径的定义是从根节点到最近子节点的最短路径,必须是子节点[1,2]正确输出应该是2,如果不判断左子节点和右子节点输出就会变成1.

  [1,2]:       [1,2,3]   

    1        1
   /        /
   2        2
           /
          3

  思路:

    我的思路:首先判断root是否等于NULL,然后直接使用递归。

    leetcode:1.判断root是否为NULL,2.判断root->left是否为空,3.判断root->right是否为空,4.利用递归,每次加1计算长度。

  代码:

1 class Solution {
2 public:
3     int minDepth(TreeNode* root) {
4         if (root == NULL) return 0;
5         if (root->left == NULL) return minDepth(root->right) + 1;
6         if (root->right == NULL) return minDepth(root->left) + 1;
7         return min(minDepth(root->left), minDepth(root->right)) + 1;
8     }
9 };

  出错代码1:

    没有判断左子节点和右子节点为空的情况,若不判断在1,2这种情况就返回1,但是正确应该是返回2,题目是说从根节点到子节点。

1 class Solution {
2 public:
3     int minDepth(TreeNode* root) {
4         if (root == NULL) return 0;
5         return min(minDepth(root->left), minDepth(root->right)) + 1;
6     }
7 };

  我的测试代码:

 1 // Minimum Depth of Binary Tree.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "iostream"
 6 #include "malloc.h"
 7 #include "algorithm"
 8 using namespace std;
 9 
10 struct TreeNode
11 {
12     int val;
13     TreeNode *left, *right;
14     TreeNode(int x) :val(x), left(NULL), right(NULL){};
15 };
16 
17 void creatTree(TreeNode* &T)
18 {
19     int data;
20     cin >> data;
21     if (data == -1)
22     {
23         T = NULL;
24     }
25     else
26     {
27         T = (TreeNode*)malloc(sizeof(TreeNode));
28         T->val = data;
29         creatTree(T->left);
30         creatTree(T->right);
31     }
32 
33 }
34 
35 class MyClass
36 {
37 public:
38     int minDepth(TreeNode* root)
39     {        if (root == NULL) return 0;
40         if (root->left == NULL) return minDepth(root->right) + 1;        //leetcode上1,2这样最短是返回2,而不是1 
41         if (root->right == NULL) return minDepth(root->left) + 1;        //题目中有说是从根节点到最近的叶子节点,必须时到叶子节点啊
42         return min(minDepth(root->left), minDepth(root->right)) + 1;
43 
44     }
45 
46 };
47 
48 int _tmain(int argc, _TCHAR* argv[])
49 {
50     TreeNode* root = NULL;
51     int m = 0;
52     creatTree(root);
53     MyClass solution;
54     m = solution.minDepth(root);
55     cout << m << endl;
56     system("pause");
57     return 0;
58 }

 

posted on 2016-06-26 18:16  zhuzhu2016  阅读(211)  评论(0)    收藏  举报

导航