Kotlin. Beats 100% (66 ms). Using IntArray as a stack to build a path
CodeApproachLet's build a full new tree for the first elements from 0 to 14:We can see that there is some pattern in the elements.Odd elements are always to the
![image.png](https://assets.leetcode.com/users/images/565aa018-ddfd-4f5e-a335-ce80582d9ae5_1740124929.3705842.png)

# Code
```kotlin []

class FindElements(val root: TreeNode?) {

    val path = IntArray(100)
    var size = 0

    fun find(target: Int): Boolean {
        size = 0
        findPath(target)
        var node: TreeNode? = root
        while (node != null && size > 0) {
            node = if (path[--size] == 0) node?.left else node?.right
        }
        return node != null
    }

    fun findPath(target: Int) {
        var n = target
        while (n != 0) {
            if (n and 1 == 1) {
                path[size++] = 0
                n--
            } else {
                path[size++] = 1
                n--
                n--
            }
            n = n shr 1
        }
    }
}
```

# Approach

Let's build a full new tree for the first elements from 0 to 14:

![image.png](https://assets.leetcode.com/users/images/45c531e9-f862-4dc9-92fd-4e3ba9bb7691_1740126369.2539666.png)

We can see that there is some pattern in the elements.
Odd elements are always to the left of the parent: 3->7, 1->3, 4->9

![image.png](https://assets.leetcode.com/users/images/6d9af8f0-8c97-4c52-b907-97b849774ff5_1740126187.858235.png)

and even elements are always to the right: 3->8, 1->4, 4->10

![image.png](https://assets.leetcode.com/users/images/97b66e71-a698-42ef-836f-0b3d6afbdc94_1740126281.8742611.png)

So the first step to build a path in the new tree to "target" seems obvious - we need to look at the remainder of dividing "target" by 2. And if the remainder is 1, then "target" is to the left of its parent. If 0, then it is to the right.

We can avoid the "costly" operation of calculating the remainder of division by 2, and instead check the least significant bit of the number using bitwise "and":
(n and 1 == 1) 
to check if the number is odd.

Next, we need to subtract 1 from the target if this element is to the left of the parent, or 2 if it is to the right. Then divide the resulting number by 2 - this way the "target" will receive the value of its parent, i.e. we will move to a higher level in the tree.

By continuing this process to 0, we can restore the full path to "target" in the new tree. And, I note, **we don't have to change the nodes of the entire tree**.

All that remains is to take the path to the "target" and walk that path inside the tree to determine whether such a path exists or not.
['Kotlin']