二叉搜索树的第k个节点
二叉搜索树的第k个结点
http://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a
一是利用大家都能想到的中序遍历递归法:
public class Solution { List<TreeNode> list = new ArrayList<>(); TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot == null || k < 1){ return null; } minOrder(pRoot, k); //当k超过节点个数时 if(list.size() < k) return null; return list.get(k-1); } void minOrder(TreeNode pRoot, int k){ if(pRoot != null){ minOrder(pRoot.left, k); list.add(pRoot); k = k - 1; if(k == 0) return; minOrder(pRoot.right, k); } } }
二是利用栈来弹出第k个节点:
public class Solution { List<TreeNode> list = new ArrayList<>(); TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot == null || k < 1){ return null; } TreeNode node = pRoot; int count = 0; Stack<TreeNode> stack = new Stack<>(); while(!stack.isEmpty() || node != null){ //中序遍历 //遍历到左子树为空 if(node != null){ stack.push(node); node = node.left; }else{ //再弹出去 node = stack.pop(); count++; //当弹到第k个时,直接返回 if(count == k) return node; //否则,遍历右子树 node = node.right; } } return null; } }