Skip to content

515 在每个树行中找最大值

给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。

题解

利用层序遍历来实现, 在每一层中找到最大值。可以先看层序遍历的解答

javascript
var largestValues = function(root) {
 // 利用层序遍历来
 const queue = []
 const result = []

 if(!root) {
     return result
 }
 queue.push(root)
 while(queue.length) {
     const size = queue.length
     // const temp = []
     let i =0;
     let max
     while(i < size) {
         const first = queue.shift()
         if(i !== 0) {
             max = Math.max(max, first.val)
         } else {
            max = first.val
         }
         if(first.left) {
             queue.push(first.left)
         }
         if(first.right) {
             queue.push(first.right)
         }
         i++
     }
     result.push(max)
     //result.push(temp)      
 }

 return result 
};

上次更新于: