[Leetcode] 199. Binary Tree Right Side View 解题报告

来源:互联网 发布:怎么在pdf上签名 mac 编辑:程序博客网 时间:2024/06/07 13:19

题目

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <--- /   \2     3         <--- \     \  5     4       <---

You should return [1, 3, 4].

思路

这道题目的本质是一个树的遍历问题,只是我们在遍历过程中需要记录每层最右边的结点值。树的遍历有DFS和BFS两种策略,这两种策略都可以用来求解本题目。

1、DFS:我们采用先序遍历,以保证越靠近根节点的结果越处于结果前列。特殊之处在于遍历完根节点之后,先遍历右子树,再遍历左子树(这样可以保证每个层次中第一个被遍历到的结点一定是该层的最右边结点),并且维护一个还没有被遍历到的层的索引,如果当前结点的层数大于未遍历到的层数,说明我们进入了一个新层,所以将当前节点的值加入结果集中。

2、BFS:BFS求解本题目实际上更直观。我们按照层次遍历,每次遍历到一个层次的末尾时,就将该层的最右边结点的值加入结果集中。下面的代码片段采用队列这种数据结构实现了层次遍历,并采用添加NULL值这种技巧区分层。

代码

1、DFS:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> rightSideView(TreeNode* root) {        vector<int> ret;        int depth = 0;        DFS(root, 1, ret, depth);        return ret;    }private:    void DFS(TreeNode* root, int current_depth, vector<int> &ret, int &depth) {        if (!root) {            return;        }        if (depth < current_depth) {    // came to a new depth            ++depth;ret.push_back(root->val);        }        DFS(root->right, current_depth + 1, ret, depth);        DFS(root->left, current_depth + 1, ret, depth);    }};

2、BFS:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> rightSideView(TreeNode* root) {        vector<int> ret;        if (!root) {            return ret;        }        queue<TreeNode*> q;        q.push(root), q.push(NULL);        int value;        while (!q.empty()) {            TreeNode *node = q.front();            q.pop();            if (node == NULL) {         // come to the end of a layer                ret.push_back(value);                if (!q.empty()) {                    q.push(NULL);                }            }            else {                value = node->val;                if (node->left) {                    q.push(node->left);                }                if (node->right) {                    q.push(node->right);                }            }        }        return ret;    }};

阅读全文
0 0