面试题五十四:二叉搜索树的第K大节点
方法:搜索二叉树的特点就是左树小于节点,节点小于右树,所以采用中序遍历法就可以得到排序序列
BinaryTreeNode KthNode(BinaryTreeNode pNode ,int k){ if( pNode ==null||k==0) return null; return KthNodeCore(pNode ,k ); } BinaryTreeNode KthNodeCore(BinaryTreeNode pNode ,int k ){ BinaryTreeNode target=null; //遍历到最小值开始递归 if( pNode.L!=null) target=KthNodeCore(pNode.L ,k ); //k作为条件 if(target==null ){ if(k==1) target=pNpde; k--; } if( target==null && pNode.R==null) target=KthNodeCore(pNode.R ,k ); return target; }
浪波激泥