二叉搜索树的第k个结点
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
二叉搜索树,也叫二叉排序树。 特点: 左子树小于根节点, 右子树大于根节点。 后来,又引入了平衡二叉树的概念
二叉搜索树的中序遍历是递增的!!!
中序遍历,显然有两种方式:
1) 递归
2)迭代
递归代码: 总是不对????
public class Solution { private TreeNode res=null; TreeNode KthNode(TreeNode pRoot, int k) { recur( pRoot, k); return res; } void recur(TreeNode pRoot,int k){ if(pRoot==null || res!=null){ return; } recur(pRoot.left,k); if(k==1){ res=pRoot; return; } k--; recur(pRoot.right,k); } }
这个递归对了。 将 k 放到外面来,k也参与递归,会出错,不好控制。
public class Solution { private TreeNode res; private int cur=0; TreeNode KthNode(TreeNode pRoot, int k) { cur=k; recur(pRoot); return res; } void recur(TreeNode pRoot){ if(pRoot==null || res!=null) return ; recur(pRoot.left); if(cur==1) res=pRoot; cur--; recur(pRoot.right); } }
中序遍历: 递归式
class Solution { private List<Integer> res = new ArrayList<>(); public List<Integer> inorderTraversal(TreeNode root) { preOrderRecur(root); return res; } void preOrderRecur(TreeNode root){ if(root==null) return; preOrderRecur(root.left); res.add(root.val); preOrderRecur(root.right); } }
方法在运行的时候,对应着一个栈帧,当递归调用的时候,又产生了一个新的栈帧。
(慢慢 来品味递归的妙处)

中序遍历: 迭代式 ( 迭代式和递归的本质是一样的,思想的本质是一样的! 目的都是先保存现在的状态!递归通过栈帧保存之前的状态,迭代通过栈来保存前面的结点。 )
class Solution { private Stack<TreeNode> stack=new Stack<>(); public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); while(root!=null || stack.size()>0){ while(root!=null){ stack.push(root); root=root.left; } TreeNode tempNode=stack.pop(); res.add(tempNode.val); root=tempNode.right; } return res; } }
因此,这个求二叉搜索树的第k个结点,用迭代法也很好做
public class Solution { TreeNode KthNode(TreeNode pRoot, int k) { Stack<TreeNode>stack = new Stack<>(); while(pRoot!=null || stack.size()>0){ while(pRoot!=null){ stack.push(pRoot); pRoot=pRoot.left; } TreeNode tempNode=stack.pop(); if(k==1) return tempNode; k--; pRoot=tempNode.right; } return null; } }
也许会有遗憾,但是不应该在失败之前
浙公网安备 33010602011771号