leetcode 515. Find Largest Value in Each Tree Row
这是当初去CM面试时面试官出的试题,当初实现的方法效率很低
public class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> s = new Stack<TreeNode>();
if(root==null) return res;
s.push(root);
res.add(root.val);
while(!s.isEmpty()){
List<TreeNode> l = new ArrayList<TreeNode>();
while(!s.isEmpty()){
TreeNode tmp = s.pop();
if(tmp.left!=null) l.add(tmp.left);
if(tmp.right!=null) l.add(tmp.right);
}
int max = Integer.MIN_VALUE;
for(TreeNode tred:l){
s.push(tred);
if(tred.val>max) max = tred.val;
}
if(l.size()>0) res.add(max);
}
return res;
}
}
效率有所提升的常规解法:bfs
public class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Queue<TreeNode> s = new LinkedList<TreeNode>();
if(root==null) return res;
int query_cnt = 1;
s.add(root);
while(!s.isEmpty()){
int max = Integer.MIN_VALUE;
for(int i=0;i<query_cnt;i++){
TreeNode tr = s.poll();
if(tr.val>max) max = tr.val;
if(tr.left!=null) s.add(tr.left);
if(tr.right!=null) s.add(tr.right);
}
query_cnt = s.size();
res.add(max);
}
return res;
}
}
360

被折叠的 条评论
为什么被折叠?



