Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true Example 2: Input: 1 1 / \ 2 2 [1,2], [1,null,2] Output: false Example 3: Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2] Output: false 判断两个二叉树是否相等. 一:使用递归. public boolean isSameTree(TreeNode p, Tre…
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. Example 1: Input: / \ / \ [,,], [,,] Output: true Example 2:…
算法分析:这道题很简单,利用递归即可. public class SameTree { public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null) { return q == null; } if(q == null) { return p == null; } if(p.val == q.val) { return isSameTree(p.left, q.left) && isSameTree(p.right, q…
迭代版本用的是二叉树的DFS,中的root->right->left ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 给定两个二叉树,写一个函数判断他们是否是相同的. 如果两个二叉树的结构相同而且每个节点里面的值也相同,那么认为他们是相同的二叉树. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++…
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 the same value. 给定两个二叉树,判断是否完全相同. 若两个二叉树完全相同,则每个节点的左子树和右子树必然都相同. 可以采用递归方式,从根节点开始:…
给定一个二叉树,检查它是否是它自己的镜像(即,围绕它的中心对称).例如,这个二叉树 [1,2,2,3,4,4,3] 是对称的.    1   / \  2   2 / \ / \3  4 4  3但是下面这个 [1,2,2,null,3,null,3] 则不是:    1   / \  2   2   \   \   3    3说明:如果你可以递归地和迭代地解决它就奖励你点数.详见:https://leetcode.com/problems/symmetric-tree/description…
1.定义树节点类:节点值.左节点.右节点.构造器 2.先判断树是否为空的情况 3.树不为空时,判断节点所指的值是否相等,若相等,则递归判断节点的左右节点是否相同,相同则返回true /** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */p…
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).For example, this binary tree [1,2,2,3,4,4,3] is symmetric:    1   / \  2   2 / \   / \3  4 4  3 But the following [1,2,2,null,3,null,3] is not:    1   / \ …
思路:AVL树是高度平衡的二叉搜索树,这里为了清晰说明,分别判断是否为搜索树,是否为平衡树. struct TreeNode { struct TreeNode *left; struct TreeNode *right; int key; }; //这里先判断是否为二叉搜索树,其次判断是否为平衡的 bool IsAVL(TreeNode *root,int depth) { if (isBST(root)&&isBalance(root,&depth)) return true;…
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 rule is that if two nodes overlap, then…