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;
        }

 

posted @ 2019-03-14 13:21  ChuckLu  阅读(154)  评论(0编辑  收藏  举报