Leetcode513. 找树左下角的值

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值