leetcode 515. Find Largest Value in Each Tree Row

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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>