LeetCode-100.Same Tree

来源:互联网 发布:通信网络维护简介 编辑:程序博客网 时间:2024/06/03 21:51

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.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */

1、递归解法

public bool IsSameTree(TreeNode p, TreeNode q)    {        if(p == null && q == null) return true;        if(p == null || q == null) return false;        if(p.val == q.val)            return IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right);        return false;    }
2、非递归

public bool IsSameTree(TreeNode p, TreeNode q)    {         if (p == null && q == null) return true;            if (p == null || q == null) return false;            Stack<TreeNode> stack = new Stack<TreeNode>();            stack.Push(p);            stack.Push(q);            while (stack.Count!=0)            {                TreeNode tnP = stack.Pop();                TreeNode tnQ = stack.Pop();                if (tnP.val != tnQ.val)                    return false;                if ((tnP.left==null&&tnQ.left!=null) || (tnP.left != null && tnQ.left == null))                    return false;                if ((tnP.right == null && tnQ.right != null) || (tnP.right != null && tnQ.right == null))                    return false;                if (tnP.left != null && tnQ.left != null)                {                    stack.Push(tnP.left);                    stack.Push(tnQ.left);                }                if (tnP.right != null && tnQ.right != null)                {                    stack.Push(tnP.right);                    stack.Push(tnQ.right);                }            }            return true;    }



0 0
原创粉丝点击