来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。javascript
给定一棵二叉搜索树,请找出其中第k大的节点。java
示例 1:node
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 4
示例 2:数组
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 4
网络
限制:this
1 ≤ k ≤ 二叉搜索树元素个数code
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {number} k * @return {number} */ var kthLargest = function(root, k) { let arr = []; function rode(root){ if(!root) return; rode(root.left); arr.push(root.val); rode(root.right); } rode(root); console.log(arr); return arr[arr.length-k]; };
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。blog
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。ip
例如:
给定二叉树: [3,9,20,null,null,15,7],leetcode
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
节点总数 <= 1000
注意:本题与主站 102 题相同:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number[][]} */ var levelOrder = function(root) { if(!root) return []; let level = 0; let res = []; let arr = [root]; while(arr.length){ res[level] = []; let levelNum = arr.length; while(levelNum--){ let str = arr.shift(); res[level].push(str.val); if(str.left) arr.push(str.left); if(str.right) arr.push(str.right); } level++; } return res; };