Skip to content

Commit

Permalink
Create 545.Boundary of Binary Tree.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Jun 23, 2017
1 parent b4d9c58 commit cd886f0
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions Tree/545.Boundary-of-Binary-Tree/545.Boundary of Binary Tree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* 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> boundaryOfBinaryTree(TreeNode* root)
{
vector<int>results;
if (root==NULL) return results;

results.push_back(root->val);

vector<int>Left;
if (root->left!=NULL)
{
GoLeft(root->left,Left);
Left.pop_back();
}

vector<int>Bottom;
if (root->left!=NULL || root->right!=NULL)
GoBottom(root,Bottom);

vector<int>Right;
if (root->right!=NULL)
{
GoRight(root->right,Right);
Right.pop_back();
}
reverse(Right.begin(),Right.end());

for (int i=0; i<Left.size(); i++)
results.push_back(Left[i]);

for (int i=0; i<Bottom.size(); i++)
results.push_back(Bottom[i]);

for (int i=0; i<Right.size(); i++)
results.push_back(Right[i]);

return results;
}

void GoLeft(TreeNode* root, vector<int>& Left)
{
if (root==NULL) return;

Left.push_back(root->val);
if (root->left!=NULL)
GoLeft(root->left,Left);
else if (root->right!=NULL)
GoLeft(root->right,Left);
}

void GoRight(TreeNode* root, vector<int>& Right)
{
if (root==NULL) return;

Right.push_back(root->val);
if (root->right!=NULL)
GoRight(root->right,Right);
else if (root->left!=NULL)
GoRight(root->left,Right);
}

void GoBottom(TreeNode* root, vector<int>& Bottom)
{
if (root==NULL) return;
if (root->left==NULL && root->right==NULL)
{
Bottom.push_back(root->val);
}
else
{
GoBottom(root->left,Bottom);
GoBottom(root->right,Bottom);
}
}
};

0 comments on commit cd886f0

Please sign in to comment.