100. Same Tree Total Accepted: 100129 Total Submissions: 236623 Difficulty: Easy 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 t…
100. Same Tree /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} p * @param {TreeNode} q * @return {boolean} */ var isSameTree = function(p, q) { if(p…
Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys…
题目: Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that duplicates do not exist in the tree. 说明: 1)实现与根据先序和中序遍历构造二叉树相似,题目参考请进 算法思想 中序序列:C.B.E.D.F.A.H.G.J.I   后序序列:C.E.F.D.B.H.J.I.G.A   递归思路: 根据后序遍历的特点,…
1.题目描述 2.问题分析 DFS. 3.代码 bool isBalanced(TreeNode* root) { if (root == NULL) return true; && isBalanced(root->left) && isBalanced(root->right); } int height(TreeNode *node) { if (node == NULL) ; if (node->left == NULL && no…
总是在看完别人的代码之后,才发现自己的差距! 我的递归: 先把左侧扁平化,再把右侧扁平化. 然后找到左侧最后一个节点,把右侧移动过去. 然后把左侧整体移到右侧,左侧置为空. 很复杂吧! 如果节点很长的话,这个耗时是很大的.O(n^2) ?差不多了! 菜逼啊!时间估计都错了!!! 时间是多少呢? while 最左侧的数,会不断被遍历!是这样的.大概会被遍历o(n)次 所以还是O(n^2)? 反正是复杂了. void flatten(struct TreeNode* root) { if(root…
1.题目描述 2.问题分析 遍历一遍树,然后将所有节点的数值放入到一个set中,最后检查set中元素的个数是否为1. 3.代码 bool isUnivalTree(TreeNode* root) { set<int> s; preOrder(root, s); ; } void preOrder(TreeNode* root, set<int> &s) { if (root == NULL) return; s.insert(root->val); preOrder(…
我准备开始一个新系列[LeetCode题解],用来记录刷LeetCode题,顺便复习一下数据结构与算法. 1. 二叉树 二叉树(binary tree)是一种极为普遍的数据结构,树的每一个节点最多只有两个节点--左孩子结点与右孩子结点.C实现的二叉树: struct TreeNode { int val; struct TreeNode *left; // left child struct TreeNode *right; // right child }; DFS DFS的思想非常朴素:根据…
前言   [LeetCode 题解]系列传送门:  http://www.cnblogs.com/double-win/category/573499.html   1.题目描述 Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,2,3]. Note: Recursive sol…
前言   [LeetCode 题解]系列传送门:  http://www.cnblogs.com/double-win/category/573499.html   1.题目描述   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…