leetcode question 199:Binary Tree Right Side View
阿新 • • 發佈:2018-12-13
問題:
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 <---
分析:
這裡這道題要求我們輸出從右邊看到這棵樹時看到的數字,一開始考慮遮擋的情況考慮的不夠周全,想著一直向右檢索,右孩子為空時向左檢索,後面發現自己考慮的不周到。後來改用了兩個list來解決問題,有點笨,但是易懂。
程式碼:
/** * 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) { list<TreeNode*> cur; vector<int> ans; if(root == NULL ){ return ans; } cur.push_back(root); while( !cur.empty() ){ TreeNode* lastNode = cur.back(); ans.push_back(lastNode->val); list<TreeNode*> temp_nodes; while(!cur.empty()){ TreeNode* temp = cur.front(); cur.pop_front(); if(temp->left!=NULL){ temp_nodes.push_back(temp->left); } if(temp->right!=NULL){ temp_nodes.push_back(temp->right); } } cur = temp_nodes; } return ans; } };