94转载自:
https://blog.youkuaiyun.com/weixin_42130471/article/details/80403114
105转载自:
https://blog.youkuaiyun.com/qq_40163148/article/details/89214880
102转载自:
https://blog.youkuaiyun.com/zhangyumengs/article/details/80414858
236转载自:
https://blog.youkuaiyun.com/qq_38595487/article/details/80256894
297-java版本:
public class Codec {
public String serialize(TreeNode root) {
if(root == null) return "#,";
String s = String.valueOf(root.val) + ",";
s += serialize(root.left);
s += serialize(root.right);
return s;
}
int index = 0;
public TreeNode deserialize(String data) {
String[] items = data.split(",");
return helper(items);
}
TreeNode helper(String[] items){
String s = items[index++];
if(s.equals("#")) return null;
TreeNode root = new TreeNode(Integer.valueOf(s));
root.left = helper(items);
root.right = helper(items);
return root;
}
}
543:
/**
* 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 sum = 0;
int height(TreeNode* root) //求出树的高度
{
if(!root)
return 0;
int a = height(root->left);
int b = height(root->right);
sum = max(sum, a + b);
return a > b? a+1: b+1;
}
int diameterOfBinaryTree(TreeNode* root) {
height(root);
return sum;
}
};
124java版:
class Solution {
private int ret = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
getMax(root);
return ret;
}
private int getMax(TreeNode r) {
if(r == null) return 0;
int left = Math.max(0, getMax(r.left)); // 如果子树路径和为负则应当置0表示最大路径不包含子树
int right = Math.max(0, getMax(r.right));
ret = Math.max(ret, r.val + left + right); // 判断在该节点包含左右子树的路径和是否大于当前最大路径和
return Math.max(left, right) + r.val;
}
}
173C++中序遍历,用一个栈实现:
class BSTIterator {
private:
stack<TreeNode*> s;
public:
BSTIterator(TreeNode* root) {
find_left(root);
}
/** @return the next smallest number */
int next() {
TreeNode* tmp = s.top();
s.pop();
if(tmp->right!=nullptr) //如果有右子树,下一个点应该是右子树最左边的点,如果无右子树下一个点应该是其父节点,即栈顶元素
find_left(tmp->right);
return tmp->val;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if(s.empty())
return false;
return true;
}
void find_left(TreeNode* root) //找当前节点最左边的结点并一路压栈
{
while (root!=nullptr)
{
s.push(root);
root = root->left;
}
}
};