题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
代码:
<span style="color:#cc33cc;">/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.Stack; public class Solution { TreeNode KthNode(TreeNode pRoot, int k) { if(pRoot==null||k==0) return null; Stack<TreeNode> s=new Stack<TreeNode>(); s.push(pRoot); int count=0; TreeNode resNode=null; while(!s.isEmpty()){ while(!s.isEmpty()&&s.peek()!=null){ TreeNode temp=s.peek(); s.push(temp.left); } s.pop(); if(!s.isEmpty()&&s.peek()!=null){ TreeNode node=s.pop(); count++; if(count==k){ resNode=node; break; } s.push(node.right); } } return resNode; } }</span>
时间: 2024-12-19 12:45:00