最近在做LeetCode上面有关二叉树的题目,这篇博客仅用来记录这些题目的代码. 二叉树的题目,一般都是利用递归来解决的,因此这一类题目对理解递归很有帮助. 1.Symmetric Tree(https://leetcode.com/problems/symmetric-tree/description/) class Solution { public: bool isSymmetric(TreeNode* root) { return root == NULL || isMirror(roo…
leetcode tree相关题目小结 所使用的方法不外乎递归,DFS,BFS. 1. 题100 Same Tree Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value Ex…
刷完了LeetCode链表相关的经典题目,总结一下用到的技巧: 技巧 哑节点--哑节点可以将很多特殊case(比如:NULL或者单节点问题)转化为一般case进行统一处理,这样代码实现更加简洁,优雅 两个指针--链表相关的题目一般都需要用到两个指针:prev指针和cur指针 头插法--主要用于reverse链表 前后指针/slow fast指针--用于检测链表是否存在环…
1.获取全排列 https://leetcode.com/problems/permutations/submissions/ 按字典序输出: 这里用的是vector<int>,不是引用.指针,也就是说深层次中的递归不会影响到前面层vector中的数据. class Solution { public: vector<vector<int>>ans; void dfs(vector<int>arr, int k, int n) { if (k == n) {…
1.46题,全排列 https://leetcode-cn.com/problems/permutations/ class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ n = len(nums) results = [] def backtrack(first = 0): if first ==…
LeetCode:二叉树相关应用 基础知识 617.归并两个二叉树 题目 Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge ru…
暂时接触到LeetCode上与链表反转相关的题目一共有3道,在这篇博文里面总结一下.首先要讲一下我一开始思考的误区:链表的反转,不是改变节点的位置,而是改变每一个节点next指针的指向. 下面直接看看LeetCode上的题目: 206. Reverse Linked List 这是一道最基本的链表反转题目. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * Lis…
LeetCode: Palindrome 回文相关题目汇总 LeetCode: Palindrome Partitioning 解题报告 LeetCode: Palindrome Partitioning II 解题报告 Leetcode:[DP]Longest Palindromic Substring 解题报告 LeetCode: Valid Palindrome 解题报告…
leetcode二叉树题目总结 题目链接:https://leetcode-cn.com/leetbook/detail/data-structure-binary-tree/ 前序遍历(NLR) public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); preOrder(root, res); return res; } ​ public…
这几天详细了解了下二叉树的相关算法,原因是看了唐boy的一篇博客(你会翻转二叉树吗?),还有一篇关于百度的校园招聘面试经历,深刻体会到二叉树的重要性.于是乎,从网上收集并整理了一些关于二叉树的资料,及相关算法的实现(主要是Objective-C的,但是算法思想是相通的),以便以后复习时查阅. 什么是二叉树? 在计算机科学中,二叉树是每个节点最多有两个子树的树结构.通常子树被称作“左子树”和“右子树”,左子树和右子树同时也是二叉树.二叉树的子树有左右之分,并且次序不能任意颠倒.二叉树是递归定义的,…