剑指offer——二叉搜索树的第k个结点(一般)
2017-07-06 17:25
435 查看
题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
思路:
首先根据二叉搜索树的特点,根节点大于其左子树,小于其右子树。因为题目要求求出第k个节点,我们发现中序遍历得到的就是从小到大的顺序。
非递归:
更简洁的写法:
只定义一个成员变量inde,递归
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
思路:
首先根据二叉搜索树的特点,根节点大于其左子树,小于其右子树。因为题目要求求出第k个节点,我们发现中序遍历得到的就是从小到大的顺序。
public class Solution { int index = 0; TreeNode result; boolean found = false; TreeNode KthNode(TreeNode pRoot, int k) { if(k<=0) return null; if(pRoot==null||found==true) // 找到后快点跳出 return null; KthNode(pRoot.left,k); index++; if(index==k){ result = pRoot; found = true; } KthNode(pRoot.right,k); return result; } }
非递归:
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; break; } p = node.right; } return kthNode; } }
更简洁的写法:
import java.util.*; public class Solution { TreeNode KthNode(TreeNode pRoot, int k) { int index = 0; Stack<TreeNode> stack = new Stack<>(); while(pRoot!=null||!stack.isEmpty()){ while(pRoot!=null){ stack.push(pRoot); pRoot = pRoot.left; } index++; pRoot = stack.pop(); if(index==k) return pRoot; pRoot = pRoot.right; } return null; } }
只定义一个成员变量inde,递归
public class Solution { int index = 0; TreeNode KthNode(TreeNode pRoot, int k) { if(k<=0||pRoot==null) return null; TreeNode result = null; if(result==null&&pRoot.left!=null) result = KthNode(pRoot.left,k); index++; if(index==k){ return pRoot; } if(result==null&&pRoot.right!=null) result = KthNode(pRoot.right,k); return result; } }
相关文章推荐
- 《剑指Offer》之“二叉搜索树的第k个结点”
- 剑指offer面试题63 二叉搜索树的第k个结点
- 剑指offer:二叉搜索树的第k个结点
- 剑指offer——面试题63:二叉搜索树的第k个结点
- 《剑指offer》:[63]二叉搜索树的第K个结点
- python剑指offer系列二叉搜索树的第k个结点
- 剑指Offer——二叉搜索树的第k个结点
- 剑指offer——二叉搜索树的第k个结点(覆盖TreeSet的compare方法)
- 《剑指Offer》学习笔记--面试题63:二叉搜索树的第k个结点
- 剑指offer—二叉搜索树的第k个结点
- 剑指offer(59)-二叉搜索树的第k个结点
- 剑指Offer:二叉搜索树的第K个结点
- 剑指offer 面试题63:二叉搜索树的第k个结点(二叉树中序遍历的应用) 题解
- 《剑指offer》面试题63 二叉搜索树的第k个结点
- 剑指Offer_62_二叉搜索树的第k个结点
- 剑指offer--面试题63:二叉搜索树的第k个结点
- 《剑指offer》二叉搜索树的第k个结点
- 二叉搜索树的第k个结点
- 剑指offer——62.二叉搜索树的第k个结点
- 《剑指offer》刷题笔记(代码的鲁棒性):链表中倒数第k个结点