标签:queue poll int 找树 力扣 左下角 null root leftLen
513、找树左下角的值
基本思想:
树的最后一行找到最左边的值
树的最后一行:深度最大的叶子节点---前序遍历
最左边:优先左边搜索---前序遍历
具体实现:
1、确定递归参数和返回值
参数:根节点和int型变量记录深度
返回值:不需要
如果要遍历整棵树,递归函数不能有返回值
如果要遍历某一条固定路线,递归函数就一定要返回值
本题要遍历整个树找到最深的叶子节点,需要遍历整棵树,所以没有返回值
2、终止条件
遇到叶子节点,统计一下最大的深度了,所以需要遇到叶子节点来更新最大深度maxLen。
if (root.left == null && root.right == null){ if (leftLen > maxLen) { maxLen = leftLen; maxLeftValue = root.val; } return; }
3、单层递归逻辑
回溯
代码:
class Solution { private int maxLen = -1; private int maxLeftValue = 0; public int findBottomLeftValue(TreeNode root) { findLeftValue(root,0); return maxLeftValue; } private void findLeftValue (TreeNode root, int leftLen){ if (root == null) return; if (root.left == null && root.right == null){ if (leftLen > maxLen) { maxLen = leftLen; maxLeftValue = root.val; } return; } if (root.left != null){ leftLen++; findLeftValue(root.left,leftLen); leftLen--; } if(root.right != null){ leftLen++; findLeftValue(root.right,leftLen); leftLen--; } return; } }
迭代法
class Solution { public int findBottomLeftValue(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int res = 0; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode poll = queue.poll(); if (i == 0) { res = poll.val; } if (poll.left != null) { queue.offer(poll.left); } if (poll.right != null) { queue.offer(poll.right); } } } return res; } }
标签:queue,poll,int,找树,力扣,左下角,null,root,leftLen 来源: https://www.cnblogs.com/zhaojiayu/p/15549638.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。