Loading...
Loading...
You are given the root of a binary tree whose node values are all different, and an integer target that is the value of one of its nodes.
A postorder traversal visits a node after its whole left subtree and then its whole right subtree.
Return the value of the node visited right after the node with value target in a postorder traversal of the tree. If that node is visited last, return -1.
Your function receives root as a TreeNode; the node type is provided for you, with val, left and right fields.
The examples below write the tree as its level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how the input is displayed; the decoding is done for you.
Node.val ≤105, and all values are different.target is the value of a node in the tree.The postorder traversal is 4, 5, 2, 6, 3, 1. Node 5 is the right child of 2, so 2 is visited right after it.
After the left subtree of 1 (rooted at 2) comes its right subtree, rooted at 3. The first node visited there is 6, since 3 has no left child.
The postorder traversal is 30, 20, 10. The root is always visited last, so the answer is -1.