/** * 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 binary tree * @return: the maximum weight node */ int max_sum; TreeNode* max_node; TreeNode * findSubtree(TreeNode * root) { // write your code here if(root==NULL) return root; if(root->left==NULL && root->right==NULL) return root; max_sum = INT_MIN; max_node = NULL; dfs(root); return max_node; } int dfs(TreeNode* cur){ if(cur==NULL) return 0; int sum = dfs(cur->left)+dfs(cur->right)+cur->val; if(sum > max_sum){ max_sum = sum; max_node = cur; } return sum; } };
计算每个结点的高度并用一个map来存储对应的值,然后将高度从1开始到max_depth 逐层打印出来。
/** * 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 binary tree * @return: collect and remove all leaves */ int max_depth; unordered_map<int, vector<int>> depth; int dfs(TreeNode* cur){ if(cur == NULL) return 0; int d = max(dfs(cur->left), dfs(cur->right))+1; max_depth = max(max_depth, d); depth[d].push_back(cur->val); return d; } vector<vector<int>> findLeaves(TreeNode * root) { // write your code here vector<vector<int>> ans; max_depth = 0; dfs(root); for(int i=1; i<=max_depth; i++) ans.push_back(depth[i]); return ans; } };
二叉树翻转:
/** * 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 binary tree * @return: new root */ TreeNode* newRoot; TreeNode * upsideDownBinaryTree(TreeNode * root) { // write your code here if(root == NULL) return root; dfs(root); return newRoot; } void dfs(TreeNode* cur){ if(cur->left != NULL){ dfs(cur->left); cur->left->right = cur; cur->left->left = cur->right; cur->left = NULL; cur->right = NULL; } else newRoot = cur; } };