leetcode 劍指 Offer 54. 二叉搜索樹的第k大節點

【題目】劍指 Offer 54. 二叉搜索樹的第k大節點

給定一棵二叉搜索樹,請找出其中第k大的節點。

示例 1:

輸入: 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

限制:
1 ≤ k ≤ 二叉搜索樹元素個數

【解題思路1】中序遍歷 改

右根左

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int count, res;
    public int kthLargest(TreeNode root, int k) {
        count = k;
        dfs(root);
        return res;
    }

    public void dfs(TreeNode root){
        if(root == null){
            return;
        }
        //右根左,倒過來中序遍歷
        dfs(root.right); //一直找到最右邊的結點
        count--;
        if(count == 0){ //當計數爲0的時候說明找到了從後往前數的第k個數
            res = root.val;
            return;
        }
        dfs(root.left);
    }
}

【解題思路2】正常中序遍歷 + list

class Solution {
    public int kthLargest(TreeNode root, int k) {
        // 在中序遍歷的同時,把值加入表中
        List<Integer> list = new ArrayList();
        dfs(root,list);
        return list.get(list.size() - k);
    }

    // 二叉樹遞歸形式中序遍歷
    void dfs(TreeNode root, List list){
        if(root == null) return ;
        dfs(root.left,list);
        list.add(root.val);
        dfs(root.right,list);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章