最近在做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] 二叉树相关题目(不完全)的更多相关文章

  1. leetcode tree相关题目总结

    leetcode tree相关题目小结 所使用的方法不外乎递归,DFS,BFS. 1. 题100 Same Tree Given two binary trees, write a function ...

  2. [LeetCode] [链表] 相关题目总结

    刷完了LeetCode链表相关的经典题目,总结一下用到的技巧: 技巧 哑节点--哑节点可以将很多特殊case(比如:NULL或者单节点问题)转化为一般case进行统一处理,这样代码实现更加简洁,优雅 ...

  3. LeetCode - 排列相关题目

    1.获取全排列 https://leetcode.com/problems/permutations/submissions/ 按字典序输出: 这里用的是vector<int>,不是引用. ...

  4. Leetcode回溯相关题目Python实现

    1.46题,全排列 https://leetcode-cn.com/problems/permutations/ class Solution(object): def permute(self, n ...

  5. LeetCode:二叉树相关应用

    LeetCode:二叉树相关应用 基础知识 617.归并两个二叉树 题目 Given two binary trees and imagine that when you put one of the ...

  6. [LeetCode] 链表反转相关题目

    暂时接触到LeetCode上与链表反转相关的题目一共有3道,在这篇博文里面总结一下.首先要讲一下我一开始思考的误区:链表的反转,不是改变节点的位置,而是改变每一个节点next指针的指向. 下面直接看看 ...

  7. LeetCode: Palindrome 回文相关题目

    LeetCode: Palindrome 回文相关题目汇总 LeetCode: Palindrome Partitioning 解题报告 LeetCode: Palindrome Partitioni ...

  8. leetcode二叉树题目总结

    leetcode二叉树题目总结 题目链接:https://leetcode-cn.com/leetbook/detail/data-structure-binary-tree/ 前序遍历(NLR) p ...

  9. 二叉树-你必须要懂!(二叉树相关算法实现-iOS)

    这几天详细了解了下二叉树的相关算法,原因是看了唐boy的一篇博客(你会翻转二叉树吗?),还有一篇关于百度的校园招聘面试经历,深刻体会到二叉树的重要性.于是乎,从网上收集并整理了一些关于二叉树的资料,及 ...

随机推荐

  1. 【架构研习】欲善其事先利其器-Robot Framework实战演练之框架的选择

    (原创文章,转载请注明出处.) 之前有提到过,自己曾基于公司业务系统从无到有码过一套测试框架,但由于开发时的思想同时受限于公司业务及框架的适用性上,导致最终虽然框架可完美支持业务,但在易用性.兼容性及 ...

  2. react native一键分享功能实现&原理和注意点(支持微信、qq、新浪微博等)

    目前手机使用的一键分享SDK比较主流的有两个:一个是ShareSDK,另一个是友盟分享. 又因为友盟功能比较多且比较全,比如说友盟统计.友盟推送等,所以本文重点介绍的是友盟分享功能在rn上的应用以及要 ...

  3. Liunx find的运用

    find命令 一.根据 -name 查找 find[搜索范围][搜索条件] find /root -name a1 若是模糊查询,则使用通配符 *匹配任意字符{find /root -name &qu ...

  4. 解决ubuntu无法远程连接

    在装Ubantu的时候可能有的小伙伴忽略了一点,忘记了在一个地方打一下空格,导致后面无法远程连接. 如果能在这里打上对勾就可以不用后面的操作了. 首先要切换到root账号 sudo passwd ro ...

  5. js-引用类型-Array

    1.数组的操作方法 <html> <meta http-equiv="content-type" charset="utf-8" /> ...

  6. null与undefined的比较

    null在JavaScript中是关键字,它属于一个特殊的值,即空值. 而undefined它不是关键字,它表示未定义,属于预定义的全局变量. null == undefined 返回的是 true  ...

  7. eric6 中 designer 无法启动的解决办法

    1.安装环境:win10+python3.6+Eric6 2.问题:使用 pip install PyQt5 安装 PyQt5.9 版本后,发现 Eric6 中无法打开 designer.exe 工具 ...

  8. Asp.net Core中SignalR Core预览版的一些新特性前瞻,附源码(消息订阅与发送二进制数据)

    目录 SignalR系列目录(注意,是ASP.NET的目录.不是Core的) 前言 一晃一个月又过去了,上个月有个比较大的项目要验收上线.所以忙的脚不沾地.现在终于可以忙里偷闲,写一篇关于Signal ...

  9. TCP/IP协议栈 --- 网络层(IP 首部 和分片)

    IP 是TCP/IP协议栈中重要的层次, TCP UDP ICMP IGMP都是依赖IP层进行传输的.首先它是一种不可靠,无连接的协议.不可靠:它不保证IP包能正确到达目的地,无连接:表示IP并不会维 ...

  10. #openstack故障处理汇总

    ##openstack故障处理汇总 排错 openstack pike 部署 目录汇总 http://www.cnblogs.com/elvi/p/7613861.html ############# ...