199. Binary Tree Right Side View (Tree, Stack)
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> ret; TreeNode* current = root; while(current){ ret.push_back(current->val); if(current->right) current = current->right; else current = current->left; } return ret; } };
Result:Wrong Answer
Input: [1,2,3,4]
Output: [1,3]
Expected: [1,3,4]
所以,得用stack记录左边的子树
/** * 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; TreeNode* current = root; int depth = 0; //depth so far int depthGap; stack<TreeNode*> nodeStack; stack<int> depthStack; while(current){ ret.push_back(current->val); depth++; if(current->right){ if(current->left){ nodeStack.push(current->left); depthStack.push(depth); } current = current->right; } else{ current = current->left; } } while(!nodeStack.empty()){ current = nodeStack.top(); nodeStack.pop(); depthGap = depth - depthStack.top(); depthStack.pop(); while(depthGap){ depthGap--; if(current->right){ if(current->left){ nodeStack.push(current->left); depthStack.push(depth - depthGap); } current = current->right; } else{ current = current->left; } if(!current) break; } if(!current) continue; while(current){ ret.push_back(current->val); depth++; if(current->right){ if(current->left){ nodeStack.push(current->left); depthStack.push(depth); } current = current->right; } else{ current = current->left; } } } return ret; } };