LeetCode (B)

来源:互联网 发布:linux重启ssh服务 编辑:程序博客网 时间:2024/06/05 15:51


Balanced Binary TreeOct 9 '12

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of everynode never differ by more than 1.

struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {static const int IMBA = -1;int getHeight(TreeNode *root) {if(root == nullptr)return 0;int leftHeight = getHeight(root->left);if (leftHeight == IMBA)return IMBA;int rightHeight = getHeight(root->right);if (rightHeight == IMBA)return IMBA;if (abs(leftHeight - rightHeight) > 1)return IMBA;return max(leftHeight, rightHeight) + 1;}public:bool isBalanced(TreeNode *root) {return (getHeight(root) != IMBA);}};




Binary Tree Inorder TraversalAug 27 '127385 / 16684

Given a binary tree, return the inorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,3,2].

class Solution {public:        vector<int> inorderTraversal(TreeNode *root) {                vector<int> res;                if (root == NULL) return res;                stack<TreeNode*> stk;                stk.push(root);                while (!stk.empty()) {                        TreeNode *tmp = stk.top();                        if (tmp->left != NULL) {                                stk.push(tmp->left);                                tmp->left = NULL;                        } else {                                res.push_back(tmp->val);                                stk.pop();                                if (tmp->right != NULL)                                        stk.push(tmp->right);                        }                }                return res;        }};

or (recursive solution)

class Solution {        vector<int> res;        void visit(TreeNode *root) {                if (root == NULL) return;                visit(root->left);                res.push_back(root->val);                visit(root->right);        }public:        vector<int> inorderTraversal(TreeNode *root) {                res.clear();                visit(root);                return res;        }};





Binary Tree Level Order TraversalSep 29 '125832 / 14746

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its level order traversal as:

[  [3],  [9,20],  [15,7]]

class Solution {public:        vector<vector<int> > levelOrder(TreeNode *root) {                vector<vector<int> > res;                if (root == NULL) return res;                queue<pair<TreeNode*, int> > q;                q.push(make_pair(root, 0));                int c = 0;                vector<int> vec;                while (!q.empty()) {                        const int d = q.front().second;                        const TreeNode *p = q.front().first;                        q.pop();                        if (d > c) {                                res.push_back(vec);                                vec.clear();                                c = d;                        }                        vec.push_back(p->val);                        if (p->left != NULL) q.push(make_pair(p->left, d + 1));                        if (p->right != NULL) q.push(make_pair(p->right, d + 1));                }                if (!vec.empty()) res.push_back(vec);                return res;        }};







Binary Tree Level Order Traversal IIOct 1 '124449 / 10092

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its bottom-up level order traversal as:

[  [15,7]  [9,20],  [3],]

class Solution {public:        vector<vector<int> > levelOrderBottom(TreeNode *root) {                vector<vector<int> > res;                if (root == NULL) return res;                queue<pair<TreeNode*, int> > q;                q.push(make_pair(root, 0));                int c = 0;                vector<int> vec;                while (!q.empty()) {                        const int d = q.front().second;                        const TreeNode *p = q.front().first;                        q.pop();                        if (d > c) {                                res.push_back(vec);                                vec.clear();                                c = d;                        }                        vec.push_back(p->val);                        if (p->left != NULL) q.push(make_pair(p->left, d + 1));                        if (p->right != NULL) q.push(make_pair(p->right, d + 1));                }                if (!vec.empty()) res.push_back(vec);                reverse(res.begin(), res.end());                return res;        }};





Binary Tree Zigzag Level Order TraversalSep 29 '124378 / 12129

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its zigzag level order traversal as:

[  [3],  [20,9],  [15,7]]

class Solution {public:        vector<vector<int> > zigzagLevelOrder(TreeNode *root) {                vector<vector<int> > res;                if (root == NULL) return res;                queue<pair<TreeNode*, int> > q;                q.push(make_pair(root, 0));                int c = 0;                vector<int> vec;                while (!q.empty()) {                        const int d = q.front().second;                        const TreeNode *p = q.front().first;                        q.pop();                        if (d > c) {                                res.push_back(vec);                                vec.clear();                                c = d;                        }                        vec.push_back(p->val);                        if (p->left != NULL) q.push(make_pair(p->left, d + 1));                        if (p->right != NULL) q.push(make_pair(p->right, d + 1));                }                if (!vec.empty()) res.push_back(vec);                vector<vector<int> >::iterator it = res.begin();                bool f = false;                while (it != res.end()) {                        if (f) reverse(it->begin(), it->end());                        f = !f;                        ++it;                }                return res;        }};







Binary Tree Maximum Path SumNov 8 '127312 / 26768

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1      / \     2   3

Return 6.

class Solution {        void copy(TreeNode *root, TreeNode *rt) {                if (root == NULL) return;                TreeNode *l = NULL, *r = NULL;                if (root->left != NULL) l = new TreeNode(root->left->val);                if (root->right != NULL) r = new TreeNode(root->right->val);                rt->left = l, rt->right = r;                copy(root->left, rt->left);                copy(root->right, rt->right);        }        void calc(TreeNode *tree) {                if (tree == NULL) return;                calc(tree->left);                calc(tree->right);                tree->val += max(max(0, (tree->left == NULL ? 0 : tree->left->val)),                                 (tree->right == NULL ? 0 : tree->right->val));        }        void comp(TreeNode *tree, TreeNode *root, int &ans) {                if (tree == NULL) return;                int tmp = root->val;                ans = max(tmp, ans);                tmp = root->val                    + (tree->left == NULL ? 0 : tree->left->val);                ans = max(tmp, ans);                tmp = root->val                    + (tree->right == NULL ? 0 : tree->right->val);                ans = max(tmp, ans);                tmp = root->val                    + (tree->left == NULL ? 0 : tree->left->val)                    + (tree->right == NULL ? 0 : tree->right->val);                ans = max(tmp, ans);                comp(tree->left, root->left, ans);                comp(tree->right, root->right, ans);        }public:        int maxPathSum(TreeNode *root) {                if (root == NULL) return 0;                TreeNode *rt = new TreeNode(root->val);                copy(root, rt);                calc(rt);                int ans = INT_MIN;                comp(rt, root, ans);                return ans;        }};








Best Time to Buy and Sell StockOct 30 '127527 / 16932

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

class Solution {public:        int maxProfit(vector<int> &prices) {                int ans = 0, low = INT_MAX;                for (vector<int>::iterator it = prices.begin(); it != prices.end(); ++it) {                        ans = max(ans, (*it) - low);                        low = min(low, (*it));                }                return ans;        }};






Best Time to Buy and Sell Stock IIOct 31 '126007 / 11762

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

class Solution {public:        int maxProfit(vector<int> &prices) {                const int n = prices.size();                if (n == 0) return 0;                int ans = 0, low = prices[0];                for (int i = 1; i < n; ++i) {                        if (prices[i] <= prices[i - 1]) {                                ans += (prices[i - 1] - low);                                low = prices[i];                        }                }                ans += (prices[n - 1] - low);                return ans;        }};







Best Time to Buy and Sell Stock IIINov 7 '126064 / 18525

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

class Solution {public:        int maxProfit(vector<int> &prices) {                int ans = 0, low = INT_MAX, high = 0;                vector<int> left, right;                for (vector<int>::const_iterator it = prices.begin(); it != prices.end(); ++it) {                        ans = max(ans, (*it) - low);                        low = min(low, (*it));                        left.push_back(ans);                }                reverse(prices.begin(), prices.end());                ans = 0;                for (vector<int>::const_iterator it = prices.begin(); it != prices.end(); ++it) {                        ans = max(ans, high - (*it));                        high = max(high, (*it));                        right.push_back(ans);                }                reverse(right.begin(), right.end());                ans = 0;                const int n = prices.size();                for (int i = 0; i < n; ++i)                        ans = max(ans, left[i] + right[i]);                return ans;        }};// quadratic complexity does not work// O(n) works ok





Binary Tree Preorder Traversal

 Total Accepted: 2382 Total Submissions: 7137My Submissions

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

class Solution {public:        vector<int> preorderTraversal(TreeNode *root) {                vector<int> res;                if (root == NULL) return res;                set<TreeNode*> visited;                stack<TreeNode*> stk;                stk.push(root);                while (!stk.empty()) {                        TreeNode *tmp = stk.top();                        if (visited.find(tmp) == visited.end()) {                                res.push_back(tmp->val);                                visited.insert(tmp);                        }                        if (tmp->left != NULL) {                                stk.push(tmp->left);                                tmp->left = NULL;                        } else {                                stk.pop();                                if (tmp->right != NULL)                                        stk.push(tmp->right);                        }                }        }};





Binary Tree Postorder Traversal

 Total Accepted: 1838 Total Submissions: 6150My Submissions

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

class Solution {public:        vector<int> postorderTraversal(TreeNode *root) {                vector<int> res;                if (root == NULL) return res;                stack<TreeNode*> stk;                stk.push(root);                while (!stk.empty()) {                        TreeNode *tmp = stk.top();                        if (tmp->left != NULL) {                                stk.push(tmp->left);                                tmp->left = NULL;                        } else if (tmp->right != NULL) {                                stk.push(tmp->right);                                tmp->right = NULL;                        }                        else {                                stk.pop();                                res.push_back(tmp->val);                        }                }        }};







原创粉丝点击