Leetcode 513.找树左下角的值
题目要求
示例 1:

输入: root = [2,1,3]
输出: 1
示例 2:

输入: [1,2,3,4,null,5,6,null,null,7]
输出: 7
层序遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
class Solution { public int findBottomLeftValue(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int res = 0;
while (!queue.isEmpty()) { List<Integer> list = new ArrayList<>(); int size = queue.size(); while (size > 0) { TreeNode node = queue.poll(); if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); list.add(node.val); size--; }
res = list.get(0); } return res; } }
|
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
class Solution { private int maxDepth = -1; private int res = 0;
public int findBottomLeftValue(TreeNode root) { res = root.val; findLeftValue(root,0); return res; } private void findLeftValue(TreeNode root, int depth) { if (root == null) return; if (root.left == null && root.right == null) { if (depth > maxDepth) { res = root.val; maxDepth = depth; } }
if (root.left != null) findLeftValue(root.left, depth + 1); if (root.right != null) findLeftValue(root.right,depth + 1); } }
|