/*目的:求二叉树最大直径
返回值:int
输入:TreeNode
**/
/**
* 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:
int result=0;
int dfs(TreeNode* root)
{
if(nullptr==root)
return 0;
int left_height=dfs(root->left);
int right_height=dfs(root->right);
result = max(left_height + right_height, result);
return max(left_height,right_height)+1;
}
int diameterOfBinaryTree(TreeNode* root) {
if(nullptr==root)
return 0;
dfs(root);
return result;
}
};
学习一下二叉树,感觉这儿算法思想有点非常规,但也说不出来哪里。
/*目的:求二叉树坡度
一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。
整个树的坡度就是其所有节点的坡度之和。
返回值:int
输入:TreeNode
**/
/**
* 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:
int findTilt(TreeNode* root) {
if (nullptr == root)
{
return 0;
}
return std::abs(dfs(root->left) - dfs(root->right)) + findTilt(root->left) + findTilt(root->right);
}
private:
int dfs(TreeNode* root)
{
if (nullptr == root)
{
return 0;
}
return root->val + dfs(root->left) + dfs(root->right);
}
};