94. Binary Tree Inorder Traversal && 230. Kth Smallest Element in a BST
public List<Integer> inorderTraversal(TreeNode root) { Deque<TreeNode> nodes = new ArrayDeque<TreeNode>(); List<Integer> visits = new LinkedList<Integer>(); TreeNode next = root; while(!nodes.isEmpty() || next != null) { if(next != null) { nodes.push(next); next = next.left; } else { TreeNode processing = nodes.pop(); visits.add(processing.val); next = processing.right; } } return visits; }
230. Kth Smallest Element in a BST
Given a binary search tree, write a functionkthSmallest to find the kth smallest element in it.Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int kthSmallest(TreeNode root, int k) { Deque<TreeNode> nodes = new ArrayDeque<TreeNode>(); TreeNode next = root; while(!nodes.isEmpty() || next != null) { if(next != null) { nodes.push(next); next = next.left; } else { TreeNode processing = nodes.pop(); //visit processing. if(k == 1) return processing.val; --k; next = processing.right; } } return Integer.MAX_VALUE; } }

浙公网安备 33010602011771号