[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的一篇博客(你会翻转二叉树吗?),还有一篇关于百度的校园招聘面试经历,深刻体会到二叉树的重要性.于是乎,从网上收集并整理了一些关于二叉树的资料,及 ...
随机推荐
- websocket做手机页面聊天与PC页面聊天一对一的即时通讯
当时要写这个需求的时候,很头痛,手机端页面的客服功能,相当于QQ这样一个一对一聊天室功能了,瞬间蒙蔽的我也不知道用什么去写这个东西,一开始用ajax,定时器去写,写着写着发现这尼玛不在同一个页面怎么做 ...
- css3 ajax加载进度线
最近想了想ajax加载时的进项,便着手写了这个,我想css3的支持度已经够了 <button onclick="start()">button</button&g ...
- tab面板,html+css
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- Linux下执行ls命令提示CMake Error错误
一.系统环境 Fedora10 二.出错情况 执行ls命令出现如下错误提示: CMake Error: The source directory "/etc/--color=auto&quo ...
- 《java.util.concurrent 包源码阅读》19 PriorityBlockingQueue
前面讲ScheduledThreadPoolExecutor曾经重点讲到了DelayedWorkQueue,这里说的PriorityBlockingQueue其实是DelayedWorkQueue的简 ...
- Oracle11g静默安装dbca,netca报错处理--直接跟换操作系统
最近给一个客户安装oracle 11gr2 概述: 操作系统:linux 32位操作系统 [oracle@nbsrfx response]$ uname -aLinux nbsrfx 2.6.32-5 ...
- python并发编程之多进程二
一,multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu_count()查看),在python中大部分情况需要使用多进程.P ...
- 【LintCode·容易】字符串置换
字符串置换 描述: 给定两个字符串,请设计一个方法来判定其中一个字符串是否为另一个字符串的置换. 置换的意思是,通过改变顺序可以使得两个字符串相等. 样例: "abc" 为 &qu ...
- git操作之上传gitthub
push 失败解决方法: 分支操作: 分支操作之覆盖: 主master操作:
- 在外围获取APP的机密信息
叶孤城原创,转载须授权. 小白:偷窥狂,不,叶城主,怎么还不发起攻击,还在外围搞什么? 叶孤城:闭嘴,能外围解决的问题就不要破解,你以为你会天外飞仙啊! 小白:-- 本文解决一个问题:通过抓包分析出重 ...