Leetcode513. 找树左下角的值
题目:
给定一个二叉树,在树的最后一行找到最左边的值。
示例 1:
输入:
2
/ \
1 3
输出: 1
示例 2:
输入:
1
/ \
2 3
/ / \
4 5 6
/
7
输出:7
题解:
二叉树的遍历,从右到左的遍历,直到最后。
java代码:
/**
* 找出最左面的数值,为应对不同结构的树结构,需要在遍历右分支时先把val存一下
*
* @param root
* @return
*/
public static int findBottomLeftValue(TreeNode root) {
if (root == null) return 0;
int target = root.value;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.right != null) {
queue.add(node.right);
target = node.right.value;
}
if (node.left != null) {
queue.add(node.left);
target = node.left.value;
}
}
return target;
}