1602. Find Nearest Right Node in Binary Tree
Given the root of a binary tree and a node u in the tree, return the nearest node on the same level that is to the right of u, or return null if u is the rightmost node in its level.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 class Solution { bool find = false ; int targetLevel = -1 ; public : TreeNode* findNearestRightNode (TreeNode* root, TreeNode* u, bool moveRight = false , int level = 0 ) { if (!root) return nullptr ; if (find) { if (level == targetLevel) return root; if (moveRight) { auto res = findNearestRightNode (root->left, u, moveRight, level + 1 ); if (res) return res; } return findNearestRightNode (root->right, u, true , level + 1 ); } if (root == u) { find = true ; targetLevel = level; return nullptr ; } auto res = findNearestRightNode (root->left, u, false , level + 1 ); if (find and res != nullptr ) { return res; } return findNearestRightNode (root->right, u, find, level + 1 ); } };