topic

The biggest feature of this question is that this tree is a binary tree:

so,The inorder traversal of the binary tree itself is in order

Method 1: Layer order traversal + collection sorting

The idea is very simple, that is to add all the nodes to the List collection through layer order traversal, and then callCollections.sort(list) after sorting, find the kth smallest numberlist.get(k-1)

``````    public int kthSmallest(TreeNode root, int k) {

List<Integer> list = levelOrder(root);
Collections.sort(list);
return list.get(k-1);

}
public List<Integer> levelOrder(TreeNode root) {

List<Integer> result = new ArrayList<>();
if(root == null) return result;
queue.offer(root);
while(!queue.isEmpty()){

int count = queue.size();
for(int i =0 ;i< count ;i++){

TreeNode node =   queue.poll();
if(node.left != null)  queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return result;
}
``````

Method 2: Inorder traversal (stack or recursion)

`二叉树中序遍历得到的值序列是递增有序的`Use a list collection to receive ordered nodes and then go to the kth smallest number in the list collection area according to k

``````  List<Integer> list =new ArrayList<>();
public int kthSmallest(TreeNode root, int k) {

// dfs(root);    //递归中序
stackTree(root); //  栈中序
return list.get(k-1);

}
//递归中序
//  public void dfs(TreeNode root) {

//      if(root == null ) return ;

//      dfs(root.left);
//      dfs(root.right);
//  }

//  栈中序
public void stackTree(TreeNode root) {

Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
while(!stack.isEmpty() || root != null){

while(root != null){

stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
}
``````

Method 3 (method 2 improved): Inorder traversal (stack)

The sequence of values ​​obtained by the in-order traversal of the binary tree is in increasing order, so as long as the stack pops up an element each time, let k-1 (until k=0). One element (k= k-1 ===0, immediately returns the number of the first pop)

``````    public int kthSmallest(TreeNode root, int k) {

Deque<TreeNode> stack = new ArrayDeque<TreeNode>();
while(!stack.isEmpty() || root != null){

while(root != null){

stack.push(root);
root = root.left;
}

root = stack.pop();
k--;//每弹出一个元素，就让k--
if(k == 0) return root.val;//直到k减到0  说明该root.val就是第k小的数
root = root.right;
}
return -1;
}

``````

Guess you like

Origin blog.csdn.net/weixin_45618869/article/details/132579670
Recommended
Ranking
Daily