中序遍历
利用中序遍历找出第k个不为空的结点即可
java 代码
class Solution {
private List<TreeNode> list = new ArrayList<>(); //存放中序遍历的结点
public TreeNode kthNode(TreeNode root, int k) {
helper(root);
return list.get(k - 1);
}
public void helper(TreeNode root) {
if (root.left == null) list.add(root);
else {
helper(root.left);
list.add(root);
}
if (root.right != null) helper(root.right);
}
}
java 代码
class Solution2 {
private int count = 0;
public TreeNode kthNode(TreeNode root, int k) {
if (root == null) return null;
TreeNode node = kthNode(root.left, k);
if (node != null) return node;
count++;
if (count == k) return root;
node = kthNode(root.right, k);
if (node != null) return node;
return null;
}
}