3701 · Find Nearest Right Node in Binary TreePRE
Algorithms
This topic is a pre-release topic. If you encounter any problems, please contact us via “Problem Correction”, and we will upgrade your account to VIP as a thank you.
Description
Given a binary tree with a root node root and a node u in the tree, return the node value val of the right-hand node nearest to it in the layer in which the node u is located, or -1 if the node u is the rightmost node in the current layer.
The total number of nodes is between
All nodes in the tree have node values that are unique
u is a node in a binary tree rooted at root
Example
Example 1:
Input:
root = {1,2,3,#,4,5,6}
u = 2
Output:
3
Explanation:
As shown in the figure, in the layer where node 2 is located, the nearest right node is node 3
3701_1.png
Example 2:
Input:
root = {3,1,#,#,2}
u = 1
Output:
-1
Explanation:
As shown in the figure, the layer where node 1 is located has only one node and the nearest right node is not found
解法1:遍历
采用前序遍历。当找到目标节点后,记住当前层次。那么,前序遍历再次到达该层次的时候,访问到的节点就是所求节点。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary tree
* @param u: A node in root
* @return: Node value of the right node
*/
int findNearestRightNode(TreeNode *root, TreeNode *u) {
helper(root, 0, u);
if (findNode) return findNode->val;
return -1;
}
private:
bool find = false;
int targetDepth = -1;
TreeNode *findNode = NULL;
void helper(TreeNode *root, int depth, TreeNode *u) {
if (!root) return;