LeetCode (B)



Balanced Binary Tree Oct 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 Traversal Aug 27 '12 7385 / 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 Traversal Sep 29 '12 5832 / 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 II Oct 1 '12 4449 / 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 Traversal Sep 29 '12 4378 / 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 Sum Nov 8 '12 7312 / 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 Stock Oct 30 '12 7527 / 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 II Oct 31 '12 6007 / 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 III Nov 7 '12 6064 / 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: 7137 My 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: 6150 My 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);
                        }
                }
        }
};







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值