LeetCode——二叉树水题
来源:互联网 发布:淘宝人脸验证失败 编辑:程序博客网 时间:2024/06/05 13:21
Minimum Depth of Binary Tree
链接:http://leetcode.com/onlinejudge#question_111
原题:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
思路:这是一道水题,仔细点就行了。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int minDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return 0; if (root->left && root->right) { int leftDepth = minDepth(root->left); int rightDepth = minDepth(root->right); return (leftDepth < rightDepth ? leftDepth : rightDepth) + 1; } else { if (root->left) return minDepth(root->left) + 1; else if (root->right) return minDepth(root->right) + 1; else return 1; } }};
Balanced Binary Tree
链接:http://leetcode.com/onlinejudge#question_110
原题:
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 ofevery node never differ by more than 1.
思路:计算一下左右子树的高度,然后判断。
代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isBalanced(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return true; int diff = height(root->left) - height(root->right); if (diff > 1 || diff < -1) return false; else return isBalanced(root->left) && isBalanced(root->right); } private: int height(TreeNode *tree) { if (tree == NULL) return 0; int leftHeight = height(tree->left); int rightHeight = height(tree->right); int max = leftHeight > rightHeight ? leftHeight : rightHeight; return max + 1; }};
Flatten Binary Tree to Linked List
链接:http://leetcode.com/onlinejudge#question_114
原题:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
思路:前序遍历,然后链接
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void flatten(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function linkNodes(root); }private: TreeNode * linkNodes(TreeNode *tree) { if (tree == NULL) return NULL; if (!tree->left && !tree->right) return tree; TreeNode *leftLast = linkNodes(tree->left); TreeNode *rightLast = linkNodes(tree->right); if (leftLast) { leftLast->right = tree->right; tree->right = tree->left; tree->left = NULL; } return rightLast ? rightLast : leftLast; }};
Path Sum
链接:http://leetcode.com/onlinejudge#question_112
原题:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
思路:小心叶子节点的判断,有负数。
代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool hasPathSum(TreeNode *root, int sum) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) { return false; } if (!root->left && !root->right) { if (sum == root->val) return true; else return false; } if (hasPathSum(root->left, sum - root->val)) return true; else return hasPathSum(root->right, sum - root->val); }};
Path Sum II
链接:http://leetcode.com/onlinejudge#question_113
原题:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5]]
思路:和上一题相似
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<vector<int> > pathSum(TreeNode *root, int sum) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > collection; vector<int> path; pathSum(root, sum, path, collection); return collection; } private: void pathSum(TreeNode *root, int sum, vector<int> &path, vector<vector<int> > &collection) { if (root == NULL) return; path.push_back(root->val); if (!root->left && !root->right) { if (sum == root->val) collection.push_back(path); } else { pathSum(root->left, sum - root->val, path, collection); pathSum(root->right, sum - root->val, path, collection); } path.pop_back(); }};
Convert Sorted Array to Binary Search Tree
链接:http://leetcode.com/onlinejudge#question_113
原题:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:每次取链表的中间值作为树根,然后递归执行
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode *sortedListToBST(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function if (head == NULL) return NULL; TreeNode *root; int length = listLength(head); convert(root, head, length); return root; }private: void convert(TreeNode * &root, ListNode *head, int length) { if (length <= 0) return; ListNode *midPtr = getMid(head, length); root = new TreeNode(midPtr->val); convert(root->left, head, length/2); if (length % 2) convert(root->right, midPtr->next, length/2); else convert(root->right, midPtr->next, length/2-1); } ListNode* getMid(ListNode *head, int length) { ListNode *lptr = head; for (int i=0; i<length/2 && lptr; i++) lptr = lptr->next; return lptr; } int listLength(ListNode *head) { int length = 0; while (head) { length++; head = head->next; } return length; }};
Binary Tree Level Order Traversal II
链接:http://leetcode.com/onlinejudge#question_107原题:
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],]
思路:从树根开始,一层层遍历放到一个stack中,然后pop出来就以了。
代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<vector<int> > levelOrderBottom(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > collection; if (root == NULL) return collection; vector<TreeNode*> layer; layer.push_back(root); stack<vector<TreeNode*> > s; s.push(layer); while (true) { vector<TreeNode*> cur; vector<TreeNode*> &pre = s.top(); for (vector<TreeNode*>::iterator itr = pre.begin(); itr != pre.end(); itr++) { TreeNode *ptr = *itr; if (ptr->left) cur.push_back(ptr->left); if (ptr->right) cur.push_back(ptr->right); } if (cur.empty()) break; s.push(cur); } while (!s.empty()) { vector<int> vec; vector<TreeNode*> &top = s.top(); for (vector<TreeNode*>::iterator itr = top.begin(); itr != top.end(); itr++) { vec.push_back((*itr)->val); } collection.push_back(vec); s.pop(); } return collection; }};
Same Tree
链接:http://leetcode.com/onlinejudge#question_100
原题:
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
思路:递归
代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isSameTree(TreeNode *p, TreeNode *q) { // Start typing your C/C++ solution below // DO NOT write int main() function if (p==NULL && q==NULL) return true; else if (p!=NULL && q!=NULL) { if (p->val != q->val) return false; return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } else return false; }};
Symmetric Tree
链接:http://leetcode.com/onlinejudge#question_101
原题:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
思路:我是用非递归实现到,用了两个队列,一个从左到右进队列,另一个从右到左进队列
然后比较。
代码:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isSymmetric(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return true; queue<TreeNode*> lq; queue<TreeNode*> rq; lq.push(root->left); rq.push(root->right); while (!lq.empty() && !rq.empty()) { TreeNode *lptr = lq.front(); TreeNode *rptr = rq.front(); lq.pop(); rq.pop(); if (lptr==NULL && rptr==NULL) continue; else if (lptr && rptr) { if (lptr->val != rptr->val) return false; lq.push(lptr->left); lq.push(lptr->right); rq.push(rptr->right); rq.push(rptr->left); } else return false; } if (lq.empty() && rq.empty()) return true; else return false; }};
Construct Binary Tree from Inorder and Postorder Traversal
链接:http://leetcode.com/onlinejudge#question_106
原题:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路:因为不存在相同的元素,所以每次找postorder最后一个元素(即树根)在inorder的位置,
然后分成两棵子树递归进行。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function TreeNode *root = NULL; build(root, inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1); return root; }private: void build(TreeNode *&root, const vector<int> &inorder, int inLeft, int inRight, const vector<int> &postorder, int postLeft, int postRight) { if (inLeft > inRight) return; int n; for (n = inLeft; n <= inRight; n++) if (inorder[n] == postorder[postRight]) break; root = new TreeNode(inorder[n]); build(root->left, inorder, inLeft, n-1, postorder, postLeft, postLeft+(n-inLeft-1)); build(root->right, inorder, n+1, inRight, postorder, postLeft+(n-inLeft), postRight-1); }};
- LeetCode——二叉树水题
- LeetCode -- 二叉树水题II
- LeetCode—二叉树遍历的情况
- LeetCode—二叉树的建立
- LeetCode—二叉树的遍历
- leetcode笔记—判断查找二叉树
- leetCode 笔记 ————二叉树最小深度
- Leetcode-Symmetric Tree——判断二叉树是否对称
- LeetCode—判断是否为二叉搜索树
- LeetCode—二叉树的最大最小深度
- 使用迭代法对二叉树进行后序遍历——Leetcode系列(六)
- 使用迭代法对二叉树进行前序遍历——Leetcode系列(七)
- 动态规划——Unique Binary Search Trees 独一无二的二叉搜索树【LeetCode】
- LeetCode—***Binary Tree Inorder Traversal二叉树的中序遍历
- LeetCode—Binary Tree Zigzag Level Order Traversal 二叉树的Z扫描
- leetcode:构建二叉树
- 重建二叉树 leetcode
- [leetcode]二叉树先序遍历
- 第六堂课后作业
- Spring 3.0 注解注入详解
- 设计模式C++学习笔记之九(Template Method模板方法模式)
- 掌握设计模式
- git gitweb 服务器假设与配置
- LeetCode——二叉树水题
- 注意Hibernate4在开发当中的一些改变
- HTTP GET和POST区别
- Dash:程序员的的好帮手
- java IP地址,端口校验+下拉菜单选框监听事件+模拟QQ发送按钮旁的小箭头功能
- Spring事务深入浅出
- NYOJ - The Triangle(经典dp)
- HDU 湫湫系列故事——设计风景线
- zendmd获取全部已经设置的事件转换