zoukankan      html  css  js  c++  java
  • 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;
            }
  • 相关阅读:
    AWR报告生成
    ios-html-get/post差额,简而言之(MS)CheckST
    2015第33周一
    2015第32周日
    2015第32周六
    2015第32周五
    2015第32周四
    2015第32周三
    2015第32周二
    2015第32周一
  • 原文地址:https://www.cnblogs.com/chucklu/p/10529697.html
Copyright © 2011-2022 走看看