本文主要是介绍代码随想录——找树左下角的值(Leetcode513),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接
层序遍历
思路:使用层序遍历,记录每一行 i = 0 的元素,就可以找到树左下角的值
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int findBottomLeftValue(TreeNode root) {Deque<TreeNode> queue = new LinkedList<TreeNode>();int res = root.val;queue.offer(root);while(!queue.isEmpty()){int size = queue.size();for(int i = 0; i < size; i++){TreeNode node = queue.poll();if(i == 0){res = node.val;}if(node.left != null){queue.offer(node.left);}if(node.right != null){queue.offer(node.right);}}}return res;}
}
这篇关于代码随想录——找树左下角的值(Leetcode513)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!