100. Same Tree

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

二叉树有三种遍历方式,先序遍历,中序遍历以及后序遍历

采用中序遍历,进行逐结点进行比较

只要写出比较一个结点的方法就可以,然后递归调用左右子结点。

 public bool IsSameTree(TreeNode p, TreeNode q)
        {
            bool flag;
            if (p == null && q == null)
            {
                flag = true;
            }
            else if (p == null || q == null)
            {
                flag = false;
            }
            else
            {
                if (p.val == q.val)
                {
                    flag = IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right);
                }
                else
                {
                    flag = false;
                }

            }
            return flag;
        }
原文地址:https://www.cnblogs.com/chucklu/p/10529697.html