树左下角值
class Solution
{
public:
void traversal(TreeNode root, int depth, int &ret, int &maxdepth)
{
if(root->left == nullptr && root->right == nullptr)
{
if(depth > maxdepth)
{
maxdepth = depth;
ret = root->val;
}
}
if(root->left)
{
depth++;
traversal(root->left, depth, ret, maxdepth);
--depth;
}
if(root->right)
{
++depth;
traversal(root->right, depth, ret, maxdepth);
--depth;
}
}
int findBottomLeftValue(TreeNode root)
{
int depth = 1;
int ret = 0;
int maxdepth = INT_MIN;
traversal(root, depth, ret, maxdepth);
return ret;
}
};
路径总和
class Solution
{
public:
bool traversal(TreeNode root, int count)
{
if(root->left == nullptr && root->right == nullptr)
{
return count == 0;
}
if(root->left)
{
count -= root->left->val;
if(traversal(root->left, count))
{
return true;
}
count += root->left->val;
}
if(root->right)
{
count -= root->right->val;
if(traversal(root->right, count))
{
return true;
}
count += root->right->val;
}
return false;
}
bool hasPathSum(TreeNode root, int targetSum)
{
int sum = 0;
if(root)
{
targetSum -= root->val;
return traversal(root, targetSum);
}
return false;
}
};
从中序遍历和后序遍历构造二叉树
class Solution
{
public:
TreeNode *traversal(vector
{
if(postorder.empty())
{
return nullptr;
}
int rootvalue = postorder[postorder.size()-1];
TreeNode *root = new TreeNode(rootvalue);
if(postorder.size() == 1)
{
return root;
}
int i = 0;
for(; i < inorder.size(); ++i)
{
if(inorder[i] == rootvalue)
{
break;
}
}
vector
++i;
vector
vector
vector
root->left = traversal(left1, left2);
root->right = traversal(right1, right2);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
{
return traversal(inorder, postorder);
}
};
标签:return,int,traversal,depth,day13,打卡,root,postorder From: https://www.cnblogs.com/pwangikun/p/18389523