[LeetCode] 二叉树相关题目(不完全)
最近在做LeetCode上面有关二叉树的题目,这篇博客仅用来记录这些题目的代码。
二叉树的题目,一般都是利用递归来解决的,因此这一类题目对理解递归很有帮助。
1.Symmetric Tree(https://leetcode.com/problems/symmetric-tree/description/)
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return root == NULL || isMirror(root->left, root->right);
}
bool isMirror(TreeNode *left, TreeNode *right) {
if (left == NULL && right == NULL) return true;
if (left == NULL || right == NULL) return false;
if (left->val != right->val) return false;
return isMirror(left->left, right->right) && isMirror(left->right, right->left);
}
};
2.Binary Tree Level Order Traversal(https://leetcode.com/problems/binary-tree-level-order-traversal/description/)
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (root == NULL) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int layer_size = q.size();
vector<int> layer;
for (int i = ; i < layer_size; i++) {
TreeNode *temp = q.front();
q.pop();
layer.push_back(temp->val);
if (temp->left != NULL) q.push(temp->left);
if (temp->right != NULL) q.push(temp->right);
}
}
return res;
}
};
3.Binary Tree Level Order Traversal II(https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/)
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
if (root == NULL) return res;
vector<int> layer;
queue<TreeNode*> q;
q.push(root);
int count = ;
while (!q.empty()) {
TreeNode* temp = q.front();
q.pop();
count--;
layer.push_back(temp->val);
if (temp->left != NULL) q.push(temp->left);
if (temp->right != NULL) q.push(temp->right);
if (count == ) {
count = q.size();
res.push_back(layer);
layer.clear();
}
}
for (int i = ; i < res.size() / ; i++) {
vector<int> temp = res[i];
res[i] = res[res.size() - i - ];
res[res.size() - i - ] = temp;
}
return res;
}
};
4.Same Tree(https://leetcode.com/problems/same-tree/description/)
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == NULL && q == NULL) return true;
if (p == NULL || q == NULL) return false;
if (p->val != q->val) return false;
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
5.Path Sum(https://leetcode.com/problems/path-sum/description/)
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (root == NULL) return false;
if (root->left == NULL && root->right == NULL && sum == root->val) return true;
else return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
6.Path Sum II(https://leetcode.com/problems/path-sum-ii/description/)
class Solution {
public:
void helper(TreeNode *root, vector<vector<int>>& res, vector<int> t, int sum) {
if (root == NULL) return;
if (sum - root->val == && root->left == NULL && root->right == NULL) {
t.push_back(root->val);
res.push_back(t);
}
else if (root->left == NULL && root->right == NULL) {
return;
}
else {
t.push_back(root->val);
helper(root->left, res, t, sum - root->val);
helper(root->right, res, t, sum - root->val);
}
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
if (root == NULL) return res;
vector<int> t;
helper(root, res, t, sum);
return res;
}
};
7.Sum Root to Leaf Numbers(https://leetcode.com/problems/sum-root-to-leaf-numbers/description/)
class Solution {
public:
int sumNumbers(TreeNode* root) {
return helper(root, );
}
int helper(TreeNode *root, int sum) {
if (root == NULL) return ;
if (root->left == NULL && root->right == NULL) return sum * + root->val;
else return helper(root->left, sum * + root->val ) + helper(root->right, sum * + root->val);
}
};
8.Binary Tree Right Side View(https://leetcode.com/problems/binary-tree-right-side-view/description/)
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if (root == NULL) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = ; i < size; i++) {
TreeNode * temp = q.front();
q.pop();
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
if (i == size - ) {
res.push_back(temp->val);
}
}
}
return res;
}
};
9.Maximum Depth of Binary Tree(https://leetcode.com/problems/maximum-depth-of-binary-tree/description/)
递归解法:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return ;
if (root->left == NULL && root->right == NULL) return ;
int maxl = maxDepth(root->left);
int maxr = maxDepth(root->right);
return maxl > maxr ? maxl + : maxr + ;
}
};
BFS解法:
class Solution {
public:
int maxDepth(TreeNode* root) {
int res = ;
if (root == NULL) return ;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = ; i < size; i++) {
TreeNode* temp = q.front();
q.pop();
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
}
res++;
}
return res;
}
};
10.Binary Tree Inorder Traversal(https://leetcode.com/problems/binary-tree-inorder-traversal/description/)
普通的中序遍历。
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inOrder(res, root);
return res;
}
void inOrder(vector<int>& inorder, TreeNode *root) {
if (root == NULL) return;
inOrder(inorder, root->left);
inorder.push_back(root->val);
inOrder(inorder, root->right);
}
};
11.Validate Binary Search(https://leetcode.com/problems/validate-binary-search-tree/)
判断一棵二叉树是否二叉搜索树。
class Solution {
public:
bool isValidBST(TreeNode* root) {
if (root == NULL) return true;
vector<int> seq;
inOrder(seq, root);
for (int i = ; i < seq.size() - ; i++) {
if (seq[i] >= seq[i + ]) return false;
}
return true;
}
void inOrder(vector<int> &seq, TreeNode *root) {
if (root == NULL) return;
else {
inOrder(seq, root->left);
seq.push_back(root->val);
inOrder(seq, root->right);
}
}
};
12.Convert Sorted Array to Binary Search Tree(https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/)
使用分治法。
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return BSTNode(nums, , nums.size() - );
}
TreeNode* BSTNode(vector<int> &nums, int first, int last) {
if (first > last) return NULL;
else {
int mid = (first + last) / ;
TreeNode *root = new TreeNode(nums[mid]);
root->left = BSTNode(nums, first, mid - );
root->right = BSTNode(nums, mid + , last);
return root;
}
}
};
13.Balanced Binary Tree(https://leetcode.com/problems/balanced-binary-tree/description/)
判断一棵二叉树是否平衡二叉树。
/**
* 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:
bool isBalanced(TreeNode* root) {
int depth = ;
return isBalanced(root, depth);
}
bool isBalanced(TreeNode* root, int &depth) {
if (root == NULL) {
depth = ;
return true;
}
else {
int LeftDepth;
int RightDepth;
bool isLeftBalanced = isBalanced(root->left, LeftDepth);
bool isRightBalanced = isBalanced(root->right, RightDepth);
if (isLeftBalanced && isRightBalanced) {
if (abs(LeftDepth - RightDepth) <= ) {
depth = LeftDepth > RightDepth ? LeftDepth + : RightDepth + ;
return true;
} }
return false;
}
}
};
[LeetCode] 二叉树相关题目(不完全)的更多相关文章
- leetcode tree相关题目总结
leetcode tree相关题目小结 所使用的方法不外乎递归,DFS,BFS. 1. 题100 Same Tree Given two binary trees, write a function ...
- [LeetCode] [链表] 相关题目总结
刷完了LeetCode链表相关的经典题目,总结一下用到的技巧: 技巧 哑节点--哑节点可以将很多特殊case(比如:NULL或者单节点问题)转化为一般case进行统一处理,这样代码实现更加简洁,优雅 ...
- LeetCode - 排列相关题目
1.获取全排列 https://leetcode.com/problems/permutations/submissions/ 按字典序输出: 这里用的是vector<int>,不是引用. ...
- Leetcode回溯相关题目Python实现
1.46题,全排列 https://leetcode-cn.com/problems/permutations/ class Solution(object): def permute(self, n ...
- LeetCode:二叉树相关应用
LeetCode:二叉树相关应用 基础知识 617.归并两个二叉树 题目 Given two binary trees and imagine that when you put one of the ...
- [LeetCode] 链表反转相关题目
暂时接触到LeetCode上与链表反转相关的题目一共有3道,在这篇博文里面总结一下.首先要讲一下我一开始思考的误区:链表的反转,不是改变节点的位置,而是改变每一个节点next指针的指向. 下面直接看看 ...
- LeetCode: Palindrome 回文相关题目
LeetCode: Palindrome 回文相关题目汇总 LeetCode: Palindrome Partitioning 解题报告 LeetCode: Palindrome Partitioni ...
- leetcode二叉树题目总结
leetcode二叉树题目总结 题目链接:https://leetcode-cn.com/leetbook/detail/data-structure-binary-tree/ 前序遍历(NLR) p ...
- 二叉树-你必须要懂!(二叉树相关算法实现-iOS)
这几天详细了解了下二叉树的相关算法,原因是看了唐boy的一篇博客(你会翻转二叉树吗?),还有一篇关于百度的校园招聘面试经历,深刻体会到二叉树的重要性.于是乎,从网上收集并整理了一些关于二叉树的资料,及 ...
随机推荐
- 腾讯课堂web零基础
utf是国际编码 gb2312 国人发明的 gbk 补充集 想看网站源代码可以按F12 <meta name ='keywords' content='设置关键字'> <meta n ...
- django作业练习
---权限管理系统 要求: 1,登陆: a,装饰器判断用户是否已经登陆 b,用户密码使用md5发送 2,注册 a,检测用户是否已经存在,onblur+ajax光标跳出输入框时(使用ajax) 3,注销 ...
- 利用VGG19实现火灾分类(附tensorflow代码及训练集)
源码地址 https://github.com/stephen-v/tensorflow_vgg_classify 1. VGG介绍 1.1. VGG模型结构 1.2. VGG19架构 2. 用Ten ...
- Luogu P1073 最优贸易
题目描述 C 国有 n 个大城市和 m 条道路,每条道路连接这 n 个城市中的某两个城市.任意两个城市之间最多只有一条道路直接相连.这 m 条道路中有一部分为单向通行的道路,一部分为双向通行的道路,双 ...
- 操作系统学习笔记----进程/线程模型----Coursera课程笔记
操作系统学习笔记----进程/线程模型----Coursera课程笔记 进程/线程模型 0. 概述 0.1 进程模型 多道程序设计 进程的概念.进程控制块 进程状态及转换.进程队列 进程控制----进 ...
- 解决thymeleaf layout布局不生效
今天使用thymeleaf layout布局时总是不生效,特此把解决问题的步骤和几个关键点记录下来备忘. 一.检查依赖 1.thymeleaf必备maven依赖: <dependency> ...
- JAVA基础3——常见关键字解读(2)
synchronized Java语言的关键字,当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码. 用法说明 synchronized 关键字,它包括两种用法: ...
- E:I Think I Need a Houseboat-poj
E:I Think I Need a Houseboat 总时间限制: 1000ms 内存限制: 65536kB 描述 Fred Mapper is considering purchasing ...
- Jquery基础知识01
1:$(document).ready()function{}和window.onload()的区别. 1:$(document).ready()function{} 该方法等到Dom结构绘制完毕 ...
- SQL Server 2016 快照代理过程分析
概述 快照代理准备已发布表的架构和初始数据文件以及其他对象.存储快照文件并记录分发数据库中的同步信息. 快照代理在分发服务器上运行:SQLServer2016版本对快照代理做了一些比较好的优化,接下来 ...