二叉搜尋樹的第k個結點(Java實現)
阿新 • • 發佈:2019-02-04
本題為劍指offer面試題63
[程式設計題]二叉搜尋樹的第k個結點- 熱度指數:40095 時間限制:1秒 空間限制:32768K
package go.jacob.day613; import java.util.Stack; /* * 二叉樹中序遍歷的應用 * 二叉搜尋樹的中序遍歷:從小到大輸出節點 */ public class Demo1 { TreeNode KthNode(TreeNode pRoot, int k) { if (pRoot == null || k <= 0) return null; int index = 0; TreeNode kthNode = null; TreeNode node = pRoot; Stack<TreeNode> stack = new Stack<TreeNode>(); while (node != null || !stack.isEmpty()) { if (node != null) { stack.push(node); node = node.left; } else { node = stack.pop(); index++; //當遍歷到第k個節點時,跳出迴圈 if (index == k) { kthNode = node; break; } node = node.right; } } return kthNode; } } class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }