博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
面试题39 二叉树的深度
阅读量:4361 次
发布时间:2019-06-07

本文共 1247 字,大约阅读时间需要 4 分钟。

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
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 };

 

转载于:https://www.cnblogs.com/wanderingzj/p/5358781.html

你可能感兴趣的文章
python学习笔记——多线程编程
查看>>
zipline目录结构
查看>>
1. Scala概述
查看>>
Ubuntu下安装mysql与mysql workbench
查看>>
HDOJ1251解题报告【字典树】
查看>>
java 字符串zlib压缩/解压
查看>>
httpclient新旧版本分割点4.3
查看>>
实现小数据量和海量数据的通用分页显示存储过程
查看>>
JPEG文件结构
查看>>
jquery api 笔记(2) 事件 事件对象
查看>>
10.17NOIP模拟赛
查看>>
Opus 和 AAC 声音编码格式
查看>>
探索Split函数第三位参数的用法
查看>>
应用程序无法启动,因为应用程序的并行配置不正确
查看>>
Python单元测试——unittest
查看>>
The document cannot be opened. It has been renamed, deleted or moved.
查看>>
ios中@class和 #import,两种方式的讨论
查看>>
OpenStack,ceph
查看>>
Odoo 8.0 new API 之Environment
查看>>
页面传值中get和post区别
查看>>