/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { int target=1; TreeNode KthNode(TreeNode pRoot, int k) { // 找到中序遍历第k个结点 return midOrder(pRoot,k); } TreeNode midOrder(TreeNode root, int k){ if(root == null) return null; TreeNode left = midOrder(root.left,k); if(left != null) return left; // 中序遍历 if(target == k) return root; else target++; TreeNode right = midOrder(root.right,k); if(right != null) return right; return null; } }
思路:写一个辅助的dfs中序遍历函数:
1. 在中序遍历的访问部分进行判断:如果当前序号等于k,则直接向上返回该结点,提前终止不必要的递归;
2. 否则,继续往后进行中序遍历,直到序号等于k。