binary tree path
http://www.lintcode.com/en/problem/binary-tree-paths/
https://leetcode.com/problems/binary-tree-paths/
code
Leetcode 2016/12/15
/**
* 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL || p == NULL || q == NULL)
{
return NULL;
}
if(p == root || q == root)
{
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left != NULL && right != NULL)
{
return root;
}
if(left != NULL)
{
return left;
}
if(right != NULL)
{
return right;
}
return NULL;
}
};
/**
* 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<string> binaryTreePaths(TreeNode* root) {
vector<string> vec;
if(root == NULL)
{
return vec;
}
string cur;
dfs(vec, cur, root);
return vec;
}
void dfs(vector<string>& vec, string& cur, TreeNode* root)
{
if(root == NULL)
{
return ;
}
string original = cur;
cur += to_string(root->val) + "->";
if(root->left == NULL && root->right == NULL)
{
cur.pop_back();
cur.pop_back();
vec.push_back(cur);
cur = original;
return;
}
dfs(vec, cur, root->left);
dfs(vec, cur, root->right);
cur = original;
}
};
/*
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
void dfs(vector<string>& path, string& cur, TreeNode* root)
{
if(root == NULL)
{
return ;
}
string old = cur;
cur += "->";
cur += to_string(root->val);
// 坑2 leaf的判断条件
if(root->left == NULL && root->right == NULL)
{
path.push_back(cur);
}
else
{
dfs(path, cur, root->left);
dfs(path, cur, root->right);
}
// 坑3 要回退
cur = old;
}
vector<string> binaryTreePaths(TreeNode* root) {
// Write your code here
vector<string> vec;
if(root == NULL)
{
return vec;
}
// 坑1:single node tree
string cur = to_string(root->val);
if(root->left == NULL && root->right == NULL)
{
vec.push_back(cur);
return vec;
}
dfs(vec, cur, root->left);
dfs(vec, cur, root->right);
return vec;
}
};