二叉搜索树的题目
来源:互联网 发布:恶作剧软件 编辑:程序博客网 时间:2024/06/11 16:48
中序遍历二叉树的典型代码!
遍历二叉搜索树:(给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 24 6 8 中,按结点数值大小顺序第三个结点的值为4。)
递归:
public class Solution { int index = 0; TreeNode KthNode(TreeNode root, int k) { if(root != null){ TreeNode node = KthNode(root.left,k); //中序遍历! // 先遍历左子树,得到结果 if(node != null) return node; index ++; //中序操作 if(index == k) return root; node = KthNode(root.right,k); //最后!遍历右子树 if(node != null) return node; } return null; }}
非递归:
import java.util.Stack;public class Solution { int count = 0; TreeNode KthNode(TreeNode pRoot, int k) { if(count > k || pRoot == null) return null; TreeNode p = pRoot; Stack<TreeNode> LDRStack = new Stack<TreeNode>(); TreeNode kthNode = null; while(p != null || !LDRStack.isEmpty()){ while(p != null){ //中序遍历!遍历左子树入栈 LDRStack.push(p); p = p.left; } TreeNode node = LDRStack.pop(); System.out.print(node.val+","); count++; if(count == k){ kthNode = node; } p = node.right; //最后一步,读取右子树 } return kthNode; }}
阅读全文
0 0
- 二叉搜索树的题目
- 题目36:二叉搜索树
- 题目1105: 二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- 题目1009:二叉搜索树
- [翻译]理解Unity的自动内存管理
- 第六篇:深入浅出UML类图(三)
- Html5+ 二维码、音频、视频、文件等功能
- C#--WinForm图片选择对话框的使用
- iOS 跳转到手机设置各种页面
- 二叉搜索树的题目
- java中的IO流
- 那些小众却深得网友喜爱的导航网站
- 【转】解析mysql中:单表distinct、多表group by查询去除重复记录
- springboot+mybatis+oracle
- 会话
- Android进阶#(8/12)让不断升级的系统更好管理——Git 版本控制_项目协作,GitHub。
- node.js之模块
- POJ