#leetcode#513. Find Left Most Element My SubmissionsBack To Contest

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ChiBaoNeLiuLiuNi/article/details/55047779

513. Find Left Most Element
  • User Accepted: 870 
  • User Tried: 943 
  • Total Accepted: 882 
  • Total Submissions: 2399
  • Difficulty: Medium

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.


------------------------------------------------------------------------

BFS的变形题,掌握了BFS这题难度其实是EASY

变化就是记录一下每一层的第一个元素,循环的最后自然是最后一层的最左边元素

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int findLeftMostNode(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        TreeNode res = null;
        while(!queue.isEmpty()){
            int breadth = queue.size();
            for(int i = 0; i < breadth; i++){
                TreeNode cur = queue.poll();
                if(i == 0)
                    res = cur;
                if(cur.left != null)
                    queue.offer(cur.left);
                if(cur.right != null)
                    queue.offer(cur.right);
            }
        }
        
        return res.val;
    }
}

再来一个recursive的DFS写法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    int maxDepth = 0;
    int res = 0;
    public int findLeftMostNode(TreeNode root) {
        helper(root, 1);
        return res;
    }
    
    private void helper(TreeNode cur, int depth){
        if(depth > maxDepth){//第一次进入下一层必然是当层的最左节点,记录这个节点的val
            maxDepth = depth;
            res = cur.val;
        }
        if(cur.left != null) //注意先遍历左节点
            helper(cur.left, depth + 1);
            
        if(cur.right != null)
            helper(cur.right, depth + 1);
    }
}


猜你喜欢

转载自blog.csdn.net/ChiBaoNeLiuLiuNi/article/details/55047779
今日推荐