leetcode筆記:Same Tree

一. 題目描寫敘述node

Given two binary trees, write a function to check if they are equal or not.ios

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.ide

二. 題目分析spa

題目的意思很是easy,推斷兩棵樹是否一樣,遞歸,對兩棵樹的結點進行比較就能夠。code

三. 演示樣例代碼遞歸

#include <iostream>

using namespace std;

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;
        // p和q不一樣一時候到達葉節點,則剪枝
        else if ((p != NULL && q == NULL) || (p == NULL && q != NULL))
            return false;
        return (p->val == q->val) && isSameTree(p->left, q->left)
               && isSameTree(p->right, q->right);
    }
};

四. 小結it

該題屬於二叉樹的遍歷中的基礎題目,難度不大。io

相關文章
相關標籤/搜索