二叉搜索树的第k个结点
来源:互联网 发布:mac设置iphone铃声acc 编辑:程序博客网 时间:2024/06/05 10:33
题目描述:给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}
思路一:
中序遍历,即从小到大排序
import java.util.ArrayList;public class Solution { ArrayList<Integer> list = new ArrayList<>(); TreeNode KthNode(TreeNode pRoot, int k) { if (pRoot == null || k <= 0) return null; inorder(pRoot); if (k > list.size()) return null; return new TreeNode(list.get(k - 1)); } private void inorder(TreeNode root) { if (root == null) return; inorder(root.left); list.add(root.val); inorder(root.right); }}
思路二:
中序遍历
public class Solution { int index = 0; TreeNode KthNode(TreeNode pRoot, int k) { if (pRoot != null) { TreeNode node = KthNode(pRoot.left, k); if (node != null) return node; index++; if (index == k) return pRoot; node = KthNode(pRoot.right, k); if (node != null) return node; } return null; }}
思路三:
中序遍历,非递归
import java.util.Stack;public class Solution { TreeNode KthNode(TreeNode pRoot, int k) { if (pRoot == null || k <= 0) return null; Stack<TreeNode> stack = new Stack<>(); int count = 0; TreeNode node = pRoot; while (node != null || !stack.isEmpty()) { if (node != null) { stack.push(node); node = node.left; } else { node = stack.pop(); count++; if (count == k) return node; node = node.right; } } return null; }}
阅读全文
0 0
- 【二叉树】二叉搜索树的第k个结点
- 二叉搜索树第k个结点
- 【树14】二叉搜索树的第k个结点
- 剑指offerr--二叉搜索树的第k个结点
- 二叉搜索树的第k个结点
- 二叉搜索树的第k个结点
- 《剑指offer》二叉搜索树的第k个结点
- 二叉搜索树的第k个结点
- 二叉搜索树的第k个结点
- 二叉搜索树的第k个结点
- 二叉搜索树的第k个结点
- 二叉搜索树的第k个结点
- 剑指offer:二叉搜索树的第k个结点
- 58.二叉搜索树的第k个结点
- [剑指offer]二叉搜索树的第k个结点
- 二叉搜索树的第k个结点
- 二叉搜索树的第K个结点
- 二叉搜索树的第k个结点
- Golang原理之goroutine与channel
- 个人绘画
- Calendar是单例模式,两个实例的hashCode却不一样
- kettle 设置变量
- android 软键盘弹出 布局上移动
- 二叉搜索树的第k个结点
- JBPM 入门
- json对象 按字典排序
- Spark:使用Java实现所有的Transformation操作
- 【Android】EventBus实践
- HashSet以及重写equals()和hashCode()
- 要点提炼|开发艺术之 Activity
- python中多线程编程
- angularJS添加