513. 找樹左下角的值
阿新 • • 發佈:2021-12-10
給定一個二叉樹的 根節點 root,請找出該二叉樹的最底層最左邊節點的值。
假設二叉樹中至少有一個節點。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/find-bottom-left-tree-value
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航import java.util.LinkedList; class Solution { public int findBottomLeftValue(TreeNode root) { if (root == null) { return 0; } TreeNode ret = root; LinkedList<TreeNode> queue = new LinkedList<>(); TreeNode curEnd = root, nextEnd = null; queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node.left != null) { if (nextEnd == null) { ret = node.left; } nextEnd = node.left; queue.offer(node.left); } if (node.right != null) { if (nextEnd == null) { ret = node.right; } nextEnd = node.right; queue.offer(node.right); } if (node == curEnd) { curEnd = nextEnd; if (nextEnd != null) { nextEnd = null; } } } return ret.val; } public static void main(String[] args) { TreeNode n2 = new TreeNode(2); TreeNode n1 = new TreeNode(1); TreeNode n3 = new TreeNode(3); n2.left = n1; n2.right = n3; System.out.println(new Solution().findBottomLeftValue(n2)); } } 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; } }