Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of thelongest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Definition: The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree.
The diameter of a tree T is the largest of the following quantities:
- the diameter of T's left subtree
- the diameter of T's right subtree
- the longest path between leaves that goes through the root of T (this can be computed from the heights of the subtrees of T)
因此,对树求出直径就是一个不断递归,不断比较的过程。
/**
* 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 maxdep=0;
int height(const TreeNode* root)
{
if(root==NULL)
return 0;
int left=0;
int right=0;
if(root->left!=NULL)
left=height(root->left)+1;
if(root->right!=NULL)
right=height(root->right)+1;
maxdep=max(maxdep,left+right);
return max(right,left);
}
int diameterOfBinaryTree(TreeNode* root)
{
if(root==NULL) return 0;
else
{
height(root);
return maxdep;
}
}
};
Convert BST to Greater Tree
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:
Input: The root of a Binary Search Tree like this: 5 / \ 2 13 Output: The root of a Greater Tree like this: 18 / \ 20 13
根据题意,我们要找到比该节点大的所有节点再全部相加而获得该节点的新值,由二分查找树的性质,可以采用后序遍历的方式从大到小的获取节点并在此过程中累加到root上(root在递归中不断更新)。
/** * 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: void LastOrderVisit(TreeNode *root,int &sum) { if(root!=NULL) { LastOrderVisit(root->right,sum);//右子树 root->val += sum; sum = root->val; LastOrderVisit(root->left,sum);//左子树 } } TreeNode* convertBST(TreeNode* root) { if(root==NULL) return NULL; if(root) { int res=0; LastOrderVisit(root,res); return root; } } };