[LeetCode]Same Tree

来源:互联网 发布:产品网络宣传图制作 编辑:程序博客网 时间:2024/04/27 17:25

题目:

Same Tree

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.

来源:http://oj.leetcode.com/problems/same-tree/


思路:

判断树一个树节点是否相等三个条件: 是否有左节点, 是否有右节点, 值是否相等.
对两棵树同时进行深度遍历,每个结点都进行比较,当前两个结点值相同时,继续往下遍历,否则停止返回


C++ AC代码:

/** * Definition for binary tree * 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==NULL && q==NULL ) return true;        else if ( p==NULL || q==NULL ) return false;        else if (p->val==q->val){if(isSameTree(p->left,q->left) && isSameTree(p->right,q->right) )return true;            else return false;        }        else return false;    }};

运行时间:4ms

测试代码:待续。。。

0 0
原创粉丝点击