[Review] 199. Right view of a binary tree-Given a binary tree, imagine yourself standing on the right side of it, and in the order from top to bottom, return the node values that can be seen from the right side.

Subject: 199. Right View of Binary Tree

Given a binary tree, imagine yourself standing on the right side of it, and return the node values ​​that can be seen from the right side in order from top to bottom.
Insert picture description here

answer:

Method 1: Depth-first search
Idea:
We perform depth-first search on the tree. In the search process, we always visit the right subtree first. Then for each layer, the first node we see on this layer must be the rightmost node.
Algorithm: In
this way, we can store the first node of each depth visit, once we know the number of levels of the tree, we can get the final result array.

// 深度优先搜索 depth-first search
typedef struct TreeNode TreeNode;

// 通过“深度优先搜索”得到returnSize,max_depth
// d用来更新max_depth的值
void dfs(TreeNode* root, int d, int* max_depth, int* ans, int* returnSize)
{
    
    
    if (root==NULL)
        return;
    if (d > *max_depth)
    {
    
    
        *(ans + (*returnSize)++) = root->val;
        *max_depth = d;
    }
    dfs(root->right, d + 1, max_depth, ans, returnSize);
    dfs(root->left,  d + 1, max_depth, ans, returnSize);
}

int* rightSideView(TreeNode* root, int* returnSize)
{
    
    
    int* ans = malloc(sizeof(int) * 1e4);
    *returnSize = 0;
    int max_depth = -1;
    dfs(root, 0, &max_depth, ans, returnSize);
    return ans;
}

Method 2: Breadth First Search
Idea:
We can traverse the binary tree hierarchically, so for each layer, the rightmost node must be the last to be traversed. The level traversal of the binary tree can be realized by breadth first search.
Algorithm:
Perform a breadth first search, the left node is arranged before the right node, so that we visit each layer from left to right. Therefore, by keeping only the last visited node of each depth, we can get the rightmost node of each depth after traversing the complete tree. Apart from changing the stack to a queue and removing the check before rightmost_value_at_depth, the algorithm has no other changes.

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/114022107