标签:
/** * 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) { //二叉搜索树,左子如果不是空,则必小于该节点 //右子不为空,则必大于该节点。同样每个分支也都满足这个条件 Stack<TreeNode> st=new Stack<TreeNode>(); if(root==null) return 0; int res=0; int count=0; TreeNode temp=root; while(temp!=null||!st.isEmpty()) { if(temp!=null) { st.push(temp); temp=temp.left; } else if(!st.isEmpty()) { temp=st.pop(); count++; if(count==k) { res=temp.val; break; } if(temp.right!=null) temp=temp.right; else temp=null; } } return res; } }
230. Kth Smallest Element in a BST
标签:
原文地址:http://www.cnblogs.com/aguai1992/p/5347125.html