乾坤兽王,理财通收益,异世之只手遮天
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: 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
给定两个二叉树,判断他们是否相同,相同的二叉树拥有相同的结构,且节点的值也要相等。
递归求解。对于两个节点是否相同,有如下情况,当两个节点的左右节点均为空时返回true,如果两个节点,有一非空时,返回false,如果两个节点值不同时,返回false,之后递归求解节点的左右节点。
/** * 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 issametree(treenode* p, treenode* q) { if(p == nullptr && q == nullptr) return true; if(p == nullptr || q == nullptr) return false; if(p->val != q->val) return false; return issametree(p->left, q->left) && issametree(p->right, q->right); } };
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
如何在没有core文件的情况下用dmesg+addr2line定位段错误
用QT制作3D点云显示器——QtDataVisualization
网友评论