1. 程式人生 > >Leetcode[100]-Same Tree

Leetcode[100]-Same Tree

javadoc ive text des ide div -a not -s

Link: https://leetcode.com/problems/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.


思路:遞歸法推斷
假設兩棵樹根結點為p和q

  • 假設p和q都為空,則返回true;否則。
  • 假設p和q都非空。而且他們的值都相等。則推斷其左右子樹是否是類似樹。否則
  • 返回false;

代碼例如以下(C++):

/**
 * 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 && !q) return true; else if(p && q && (p->val == q->val)){ return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); }else{ return false; } } };
‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); });

    Leetcode[100]-Same Tree