【LeetCode】44 相同的树

image-20200623232244992

题目:

image-20200623232158676

思路:

递归

https://leetcode-cn.com/problems/same-tree/solution/xiang-tong-de-shu-by-leetcode/

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
  public boolean isSameTree(TreeNode p, TreeNode q) {
    // p and q are both null
    if (p == null && q == null) return true;
    // one of p and q is null
    if (q == null || p == null) return false;
    if (p.val != q.val) return false;
    return isSameTree(p.right, q.right) &&
            isSameTree(p.left, q.left);
  }
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×