[100] Leetcode same DFS tree []

Topic Link

Subject description:

Given two binary tree, write a function to check whether they are identical.

If the two are identical in structure tree, and the nodes have the same value, they are considered identical.

Ideas:

Wit I used a theorem: preorder traversal and continued to traverse a binary tree can be uniquely determined.

So I put the results of their preorder traversal keep up with the array to determine whether equal.

Postorder arrays are then kept up, and then determines whether or not equal.

But doing so there is a problem, that is, the value of the same node in the case of not judge. But by adding to the output node empty solve this problem.

I was represented by -1 empty node, it is certainly problematic.

Looked at the number of test cases, only 57 (2019-08-08 00:12:16), probably it is too weak data.

There is also a problem, I was not all right, with a C array to write, write, dead space, 10,000, this is not good, a waste of space on the one hand, on the other node more than 10,000 die. (Of course, this can be solved with a C ++ vector, can also be used to solve C)

Official explanations

Read the official solution to a problem, can not help but want to ask yourself, I am a pig it?

Why write such a complex code Yeah, obviously there are simpler, higher-performance code.

The idea is recursive, a determination of a node.

Relatively simple, straightforward look at the code can be understood.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    if(p==NULL && q==NULL) {
        return true;
    }
    if(p==NULL || q==NULL) {
        return false;
    }
    if(p->val!=q->val) { return false; } return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); }

Leverage performance that was it!

 

Guess you like

Origin www.cnblogs.com/shengwang/p/11318712.html