劍指offer(62):二叉搜尋樹的第k個結點
阿新 • • 發佈:2020-08-14
題目描述
給定一棵二叉搜尋樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,6,8) 中,按結點數值大小順序第三小結點的值為4。 思路:中序遍歷的第k個結點即為所求 C++實現 :class Solution { public: TreeNode* KthNode(TreeNode* pRoot, int k) { if(!pRoot) return NULL; stack<TreeNode*> sTree; TreeNode* p = pRoot;//臨時結點 int count = 0;//計數 while(!sTree.empty()||p){ if(p){ sTree.push(p); p = p->left; }else{ p = sTree.top(); sTree.pop(); count++; if(count==k) return p; p= p->right; } }//while return NULL; } };
java實現:
import java.util.Stack; public class Solution { TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot == null) return null; int count = 0; Stack<TreeNode> sTree = new Stack<>(); TreeNode p= pRoot;//臨時結點 while(!sTree.isEmpty()||p!=null){ while(p!=null){ sTree.add(p); p = p.left; } p = sTree.pop(); count++; if(count == k) return p; p = p.right; } return null; } }