指offer系列31:二叉树的深度

第一个小题目是求二叉树的深度的,前面做过很多二叉树的题,这个就比较简单了。

 1 class Solution {
 2 public:
 3     int max(int x, int y)
 4     {
 5         return (x > y) ? x : y;
 6     }
 7     int TreeDepth(TreeNode* pRoot)
 8     {
 9         if (pRoot == NULL)
10             return 0;
11         int left = 0, right = 0,depth=0;
12         if (pRoot->left)
13         {
14             left = TreeDepth(pRoot->left);
15         }
16         if (pRoot->right)
17         {
18             right = TreeDepth(pRoot->right);
19         }
20         return max(left,right)+1;
21 
22     }
23 };

第二个小题在第一个题的基础上也不难,主要是对于递归的掌握。

 1 class Solution {
 2 public:
 3     
 4     int max(int x, int y)
 5     {
 6         return (x > y) ? x : y;
 7     }
 8     
 9     int TreeDepth(TreeNode* pRoot)
10     {
11         if (pRoot == NULL)
12             return 0;
13 
14         int left = 0, right = 0;
15         left = TreeDepth(pRoot->left);//这里不用判断左子树和右子树是否为空,因为如果是空也能进入函数,而且前面两行可以终止递归
16         right = TreeDepth(pRoot->right);
17         return max(left,right)+1;
18 
19     }
20     bool IsBalanced_Solution(TreeNode* pRoot) {
21         if (pRoot == NULL)
22             return true;
23         //分别计算左右子树的深度
24         int left = TreeDepth(pRoot->left);
25         int right = TreeDepth(pRoot->right);
26         if (abs(left - right) <= 1)
27             return IsBalanced_Solution(pRoot->left)&& IsBalanced_Solution(pRoot->right);
28         else
29              return false;
30     }
31 };

对于树的题目,脑子里不要想太复杂的东西,按照以下步骤做就好:

1.写递归终结条件,一般是结点指针为空

2.把树想象成最简单只有3个结点的小树,想想该怎么计算

3.写递归条件,让它可以应对更复杂的树

猜你喜欢

转载自www.cnblogs.com/neverland0718/p/11184696.html