【刷題-LeetCode】199 Binary Tree Right Side View
阿新 • • 發佈:2020-07-14
- Binary Tree Right Side View
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.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
解1 層序遍歷,每一層最後一個節點肯定是最右邊的節點。在層序遍歷時,用cur表示當前層的節點數,next表示下一層節點數,每次從佇列裡面出來一個,cur減1,當cur==0時,表明當前出隊的節點已經是最右邊的,然後令cur=next, next = 0;每進隊一個節點,next增加1
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int>ans; if(root == NULL)return ans; queue<TreeNode*>q; q.push(root); int cur = 1, next = 0; while(!q.empty()){ TreeNode* tmp = q.front(); q.pop(); cur--; if(tmp->left){ q.push(tmp->left); next++; } if(tmp->right){ q.push(tmp->right); next++; } if(cur == 0){ ans.push_back(tmp->val); cur = next; next = 0; } } return ans; } };
解2 dfs
class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int>ans; if(root == NULL)return ans; dfs(root, 0, ans); return ans; } void dfs(TreeNode* node, int level, vector<int>& ans){ if(level == ans.size())ans.push_back(node->val); if(node->right)dfs(node->right, level+1, ans); if(node->left)dfs(node->left, level+1, ans); } };