加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

二叉搜索树的第k个结点

发布时间:2020-12-13 21:13:22 所属栏目:PHP教程 来源:网络整理
导读:题目 给定1颗2叉搜索树,请找出其中的第k大的结点。 解题 中序遍用时候找到第k大结点 import java.util.ArrayList; public class Solution { ArrayListTreeNode list = new ArrayListTreeNode(); TreeNode KthNode(TreeNode pRoot, int k) { inorder(pRoot);

题目

给定1颗2叉搜索树,请找出其中的第k大的结点。

解题

中序遍用时候找到第k大结点

import java.util.ArrayList; public class Solution { ArrayList<TreeNode> list = new ArrayList<TreeNode>(); TreeNode KthNode(TreeNode pRoot,int k) { inorder(pRoot); if(k<=0 || k> list.size()) return null; return list.get(k-1); } public void inorder(TreeNode root){ if(root == null) return; inorder(root.left); list.add(root); inorder(root.right); } }

利用中序遍历,记录遍历结点个数找到第k个结点

/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { int count = 0; // 记录遍历结点个数 TreeNode KthNode(TreeNode root,int k) { if(root==null|| k<=0) return null; TreeNode left = KthNode(root.left,k); if(left!=null) return left; count++; if(count == k) return root; TreeNode right = KthNode(root.right,k); if(right!=null) return right; return null; } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读