Leetcode 515 Find Largest Value in Each Tree Row

来源:互联网 发布:怎么识谱古筝知乎 编辑:程序博客网 时间:2024/05/21 19:34

You need to find the largest value in each row of a binary tree.

Example:

Input:           1         / \        3   2       / \   \        5   3   9 Output: [1, 3, 9]

DFS的问题,采用pre-order,depth来记录深度

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> largestValues(TreeNode root) {        List<Integer> result = new ArrayList<>();        dfs(root, result, 0);        return result;    }        private void dfs(TreeNode root, List<Integer> result, int depth){        if(root == null){            return;        }                if(result.size() == depth){            result.add(root.val);        }else{            result.set(depth, Math.max(result.get(depth), root.val));        }        dfs(root.left, result, depth + 1);        dfs(root.right, result, depth + 1);    }}


阅读全文
0 0
原创粉丝点击