No.513 Find Bottom Left Tree Value
来源:互联网 发布:linux系统chown指令 编辑:程序博客网 时间:2024/06/08 02:21
思路一:
利用BFS将整个数组遍历,求出最底层最左边的节点,将该节点输出。在实现过程中利用队列数据结构实现,由于给定的树的节点的数据结构中没有记录层数的成员,所以同时创建一个记录层数的队列进行相同的操作。注意当层数发生第一次变化时,即每一层最左边的节点,记录该节点。
class Solution {public: int findBottomLeftValue(TreeNode* root) { queue<TreeNode*> q; queue<int> i; q.push(root); i.push(0); int m = 0; while(!q.empty()){ TreeNode* t = q.front(); int l = i.front(); if(t->left){ q.push(t->left); i.push(l+1); } if(t->right){ q.push(t->right); i.push(l+1); } if(l>m){ root = t; } m=l; q.pop(); i.pop(); } return root->val; }};思路二:
通过递归一个函数,每次传入当前节点,当前深度的最大值,当前层数最左边的节点和当前层的深度,如果到达根节点的子节点则停止递归,否则的话遍历当前节点的左右子树,如果当前的深度大于最大深度,则更新最大深度,而第一次更新深度的值的节点一定是每一层最左边的点,记录下来。
class Solution {public: void findBottomLeftValue(TreeNode* root, int& maxDepth, int& leftVal, int depth) { if (root == NULL) { return; } //Go to the left and right of each node findBottomLeftValue(root->left, maxDepth, leftVal, depth+1); findBottomLeftValue(root->right, maxDepth, leftVal, depth+1); //Update leftVal and maxDepth if (depth > maxDepth) { maxDepth = depth; leftVal = root->val; } } //Entry function int findBottomLeftValue(TreeNode* root) { int maxDepth = 0; //Initialize leftVal with root's value to cover the edge case with single node int leftVal = root->val; findBottomLeftValue(root, maxDepth, leftVal, 0); return leftVal; }};
0 0
- No.513 Find Bottom Left Tree Value
- 513:find bottom left tree value
- 【513】 Find Bottom Left Tree Value
- LeetCode #513: Find Bottom Left Tree Value
- Leetcode 513 Find Bottom Left Tree Value
- leetcode 513 Find Bottom Left Tree Value
- LeetCode#513 Find Bottom Left Tree Value
- 513[Medium]:Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- Find Bottom Left Tree Value
- tomcat增加用户后仍提示拒绝权限的问题
- 从零开始学Spring Boot(3)——JPA
- 使用typedef 定义数组
- 《Android从菜鸟到高手》——002“面向对象思想”在Android的基本应用
- 深入分析Java ClassLoader原理
- No.513 Find Bottom Left Tree Value
- Hello R!
- Java单例模式(singleton),饿汉式和内部类的区别
- eclipse使用git上传项目到GitHub
- 日志总结-java变量类型
- thinking in java——0321学习笔记
- faster rcnn:assert (boxes[:, 2] >= boxes[:, 0]).all()分析塈VOC2007 xml坐标定义理解
- Unity3D Mesh小课堂(五)CombineMeshes合并网格
- Android动画SDK从基础到精通(AnimationForAndroid)