标签:ret return bool 相等 cti check ini for function
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.
思路:
这道题要判断树形一样,在这个基础上val一样。
共有5种树型:
1. node为null
2. node是leave
3. node只有左child
4. node只有右child
5. node有两个children
Base cases:
1和2是base case树形
先判断是不是两个node都为null,如果是,return true;
在判断是不是node一个为null一个不为null,如果是,return false;
如果两个node都是leaves, 判断val是不是相等,等则true,不等则false;
Recursive cases:
3, 4和5是recursive case树形
树形均为3: 判断val相等和左child相等
树形均为4: 判断val相等和右child相等
树形均为5: 判断val相等, 左child相等和右child相等
其他:树形不一样
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { // base case: // two nodes are both null: true // one is null and another is not: false // both are leaves: check the val of the two nodes if (p == null && q == null) { return true; } else if (p == null || q == null) { return false; } else if (p.left == null && q.left == null && p.right == null && q.right == null) { if (p.val == q.val) { return true; } else { return false; } // recursive case: } else if (p.left == null && q.left == null && p.right != null && q.right != null) { return p.val == q.val && isSameTree(p.right, q.right); } else if (p.left != null && q.left != null && p.right == null && q.right == null) { return p.val == q.val && isSameTree(p.left, q.left); } else if (p.left != null && q.left != null && p.right != null && q.right != null) { return (p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)); } else { return false; } } }
标签:ret return bool 相等 cti check ini for function
原文地址:http://www.cnblogs.com/fqmai/p/6216643.html