LeetCode 199. Binary Tree Right Side View

来源:互联网 发布:红警2网络进不去 编辑:程序博客网 时间:2024/04/30 16:03

题目链接:https://leetcode.com/problems/binary-tree-right-side-view/#/description

题目描述:

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].

两种思路:

思路一:非递归,层序遍历,先遍历右孩子,用队列实现,需要记录每一层一共有多少个节点,每次只保存队列的第一个节点

/** * 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> res;        if(root==NULL)            return res;        queue<TreeNode*> q;        q.push(root);        int oldLevel=1;        while(!q.empty()){            TreeNode* tmp=q.front();            res.push_back(tmp->val);            int newLevel=0;            while(oldLevel--){                if(q.front()->right!=NULL){                    q.push(q.front()->right);                    newLevel++;                }                if(q.front()->left!=NULL){                    q.push(q.front()->left);                    newLevel++;                }                 q.pop();            }            oldLevel=newLevel;        }        return res;    }};
思路2:

递归,记录当前深度和最大深度,只有当前深度大于最大深度时,更新最大深度,并将该节点保存。


/** * 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> res;        int maxdep=0;        dfs(res,root,maxdep,0);        return res;    }    void dfs(vector<int> &res,TreeNode* root,int &maxdep,int curdep){        if(root==NULL)            return;        if(++curdep>maxdep){            maxdep=curdep;            res.push_back(root->val);        }        dfs(res,root->right,maxdep,curdep);        dfs(res,root->left,maxdep,curdep);    }};