/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<TreeNode> list1 = new List<TreeNode>();
        List<TreeNode> list2 = new List<TreeNode>();

        void postTree(TreeNode tree, int type)
        {
            if (type == 1)
            {
                list1.Add(tree);
            }
            else
            {
                list2.Add(tree);
            }
            if (tree != null)
            {
                if (tree.left != null)
                {
                    postTree(tree.left, type);
                }
                else
                {
                    postTree(null, type);
                }

                if (tree.right != null)
                {
                    postTree(tree.right, type);
                }
                else
                {
                    postTree(null, type);
                }
            }

        }

        public bool IsSameTree(TreeNode p, TreeNode q)
        {
            postTree(p, 1);
            postTree(q, 2);

            var len1 = list1.Count;
            var len2 = list2.Count;

            if (len1 != len2)
            {
                return false;
            }
            else
            {
                for (int i = 0; i < len1; i++)
                {
                    if (list1[i] == null && list2[i] != null)
                    {
                        return false;
                    }
                    if (list1[i] != null && list2[i] == null)
                    {
                        return false;
                    }
                    if (list1[i] != null && list2[i] != null && list1[i].val != list2[i].val)
                    {
                        return false;
                    }
                }
                return true;
            }
        }
}

https://leetcode.com/problems/same-tree/#/description

 

补充一个java的实现,使用树的遍历:

 1 class Solution {
 2     public boolean isSameTree(TreeNode p, TreeNode q) {
 3         if(p==null && q == null){
 4             return true;
 5         }else if (p == null && q != null){
 6             return false;
 7         }else if(p != null && q == null){
 8             return false;
 9         }else{
10             if(p.val != q.val){
11                 return false;
12             }else{
13                 return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
14             }
15         }
16     }
17 }

 

posted on 2017-04-19 11:18  Sempron2800+  阅读(179)  评论(0编辑  收藏  举报