import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Solution54 {
public static void main(String[] args) {
TreeNode root = new TreeNode(8);
TreeNode node1 = new TreeNode(6);
TreeNode node2 = new TreeNode(10);
TreeNode node3 = new TreeNode(5);
TreeNode node4 = new TreeNode(7);
TreeNode node5 = new TreeNode(9);
TreeNode node6 = new TreeNode(11);
root.left = node1;
root.right = node2;
node1.left = node3;
node1.right = node4;
node2.left = node5;
node2.right = node6;
TreeNode node = KthNodeTwo(root, 1);
System.out.println(node.val);
}
public static TreeNode KthNode(TreeNode root, int k){
if (root == null){
return null;
}
inOrder(root);
if (k <= 0 || k > list.size()){
return null;
}
return list.get(k-1);
}
static List<TreeNode> list = new ArrayList<>();
public static List<TreeNode> inOrder(TreeNode root){
if (root == null){
return null;
}
inOrder(root.left);
list.add(root);
inOrder(root.right);
return list;
}
public static TreeNode KthNodeTwo(TreeNode root, int k){
if (root == null || k <= 0){
return null;
}
k1 = k;
KthNodeCore(root);
return target;
}
static TreeNode target = null;
static int k1 = 0;
public static void KthNodeCore(TreeNode root){
if (root == null || k1 <= 0){
return;
}
KthNodeCore(root.left);
k1--;
if (k1 == 0){
target = root;
return;
}
KthNodeCore(root.right);
}
public static TreeNode KthNodeThree(TreeNode root, int k){
if (root == null || k <= 0){
return null;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()){
while (cur != null){
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
k--;
if (k == 0){
return cur;
}
cur =cur.right;
}
return null;
}
}