leetcode 513. Find Bottom Left Tree Value

xiaoxiao2021-02-28  70

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input: 2 / \ 1 3 Output: 1

Example 2: 

Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7

Note: You may assume the tree (i.e., the given root node) is not NULL.

前序遍历最大深度的第一个会被保存

public class Solution { int max = 0, ans = 0; public int findBottomLeftValue(TreeNode root) { helper(root, 1); return ans; } private int helper(TreeNode root, int depth){ if(root==null) return 0; int left = helper(root.left, depth+1); int right = helper(root.right, depth+1); if(left==0 && right==0 && depth>max){ ans = root.val; max = depth; } return 1; } } 用bfs也可以

public int findLeftMostNode(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { root = queue.poll(); if (root.right != null) queue.add(root.right); if (root.left != null) queue.add(root.left); } return root.val; }

转载请注明原文地址: https://www.6miu.com/read-69681.html

最新回复(0)