面试题39 二叉树的深度

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     int TreeDepth(TreeNode* pRoot)
13     {
14         if (pRoot == NULL)
15             return 0;
16         int left = TreeDepth(pRoot->left);
17         int right = TreeDepth(pRoot->right);
18         return left > right ? left + 1 : right + 1;
19     }
20 };

 

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
 1 class Solution {
 2 public:
 3     
 4     bool IsBalanced(TreeNode* pRoot, int &depth) {
 5         if (pRoot == NULL){
 6             depth = 0;
 7             return true;
 8         }
 9         int left, right;
10         if (IsBalanced(pRoot->left, left) && IsBalanced(pRoot->right, right)){
11             if (abs(left - right) <= 1){
12                 depth = left > right ? left + 1 : right + 1;
13                 return true;
14             }
15         }
16         return false;
17     }
18     
19     bool IsBalanced_Solution(TreeNode* pRoot) {
20         int depth = 0;
21         return IsBalanced(pRoot, depth);
22     }
23 };

 

posted @ 2016-04-06 12:37  早杰  阅读(199)  评论(0编辑  收藏  举报