leetcode编程记录8 #107 Binary Tree Level Order Traversal II

来源:互联网 发布:it软件开发培训班 编辑:程序博客网 时间:2024/05/22 17:04

leetcode编程记录8 #107 Binary Tree Level Order Traversal II

标签(空格分隔): 日记


这次是一道比较简单的题目,题目如下:
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

题目理解与分析:题目很简单,就是找出树中所有比当前节点都大的其它节点,将找到的其它节点加到当前节点上从而得到一棵较大的树。
代码如下:

/** * 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:    vector<int> allNode;    TreeNode* convertBST(TreeNode* root) {        Traversal(root);        sum(root);        return root;    }    void sum(TreeNode* root) {        if (root != NULL) {            sum(root->right);            sum(root->left);            int oringin = root->val;            for (int i = 0; i < allNode.size(); ++i)            {                if (oringin < allNode[i]) {                    root->val += allNode[i];                }            }        }    }    void Traversal(TreeNode* root) {        if (root != NULL) {            Traversal(root->left);            Traversal(root->right);            allNode.push_back(root->val);        }    }};
阅读全文
0 0
原创粉丝点击