來源:力扣(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; };