199. 二叉树的右视图

Introduction

Question:199. 二叉树的右视图

Analysis

直接遍历,在遍历时维护一个树高的遍历,在访问一个节点时,将其节点值根据树高放入到返回数组对于位置即可(res[height]),确保左节点比右节点先访问到。遍历玩后,返回数组即得到正确的右视图。(哪种遍历都可以)

Implement

1
2
3
4
5
6
7
void rightSideView(vector<int> &res, TreeNode *root, int height) {
if (root == nullptr) return;
if (res.size() == height) { res.push_back(-1); }
res[height] = root->val;
rightSideView(res, root->left, height + 1);
rightSideView(res, root->right, height + 1);
}

One More Thing