等价二叉树-lintcode
来源:互联网 发布:手机版打字软件 编辑:程序博客网 时间:2024/05/16 12:40
看两个二叉树形状和内容是否完全相等。可以递归求解,每一个调用栈内存储两个返回的bool结果:lflag和rflag。然后返回它们的与。同样,和通常的递归思想一样,调用栈开始就要做好递归结束的判断:a、b都为NULL返回true,一个为NULL另一个不为NULL返回false,val不相同返回false。
C++代码:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @aaram a, b, the root of binary trees. * @return true if they are identical, or false. */ bool isIdentical(TreeNode* a, TreeNode* b) { return search(a, b); } bool search(TreeNode * a, TreeNode * b){ if (a == NULL && b == NULL) { return true; } if (a == NULL || b == NULL) { return false; } if (a->val != b->val) { return false; } bool lflag = search(a->left, b->left); bool rflag = search(a->right, b->right); return (lflag && rflag); }};
Python代码:
"""Definition of TreeNode:class TreeNode: def __init__(self, val): this.val = val this.left, this.right = None, None"""class Solution: """ @param a, b, the root of binary trees. @return true if they are identical, or false. """ def isIdentical(self, a, b): return self.search(a,b) def search(self,a,b): if a==None and b==None: return True if a==None or b==None: return False if a.val != b.val: return False a1 = self.search(a.left, b.left) a2 = self.search(a.right, b.right) return a1 and a2
0 0
- LintCode:等价二叉树
- lintcode ----等价二叉树
- 等价二叉树-lintcode
- 等价二叉树,lintcode
- lintcode-->等价二叉树
- lintcode,等价二叉树
- LintCode-等价二叉树
- LIntCode 等价二叉树
- 等价二叉树-LintCode
- Lintcode 等价二叉树
- LintCode 等价二叉树
- 等价二叉树-LintCode
- LintCode - 469.等价二叉树
- lintcode 469 等价二叉树
- LintCode 469-等价二叉树
- [LintCode]469.等价二叉树
- [Lintcode] #469 等价二叉树
- lintCode(469)——等价二叉树
- Guava源码学习笔记
- MATLAB 超定方程组 最小二乘法
- Android中Application的onCreate多次调用问题
- Halcon中的图像相减算子abs_diff_image和sub_image
- nefu 21最长上升子序列
- 等价二叉树-lintcode
- 关于论文的排版
- 使用异步任务下载图片~
- hdu2053Switch Game
- 小白笔记--------------------------计算机网络(2)
- CentOS 6.7安装Mahout 0.11.2
- Java语言基础(二)——函数与数组
- Fencing the Cows_usaco 5.1_凸包
- Java transient关键字使用小记