[LeetCode] 100. Same Tree

Given two binary trees, write a function to check if they are the same or not.node

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.ide

Example 1:this

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:spa

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:orm

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

相同的树。题意是给两个树,判断他们是否相同。有两种思路,bfs和dfs。bfs是按层遍历tree,将每层的node塞进queue而后弹出比较,须要注意塞进queue的顺序。此处我只实现了dfs的作法。ip

时间O(n)it

空间O(n)io

JavaScript实现function

 1 /**
 2  * @param {TreeNode} p
 3  * @param {TreeNode} q
 4  * @return {boolean}
 5  */
 6 const isSameTree = function(p, q) {
 7     // corner case
 8     if (p == null && q == null) return true;
 9     if (p == null || q == null) return false;
10 
11     // normal case
12     if (p.val == q.val) {
13         return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
14     }
15     return false;
16 };

 

Java实现class

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     public boolean isSameTree(TreeNode p, TreeNode q) {
18         if (p == null && q == null)
19             return true;
20         if (p == null || q == null)
21             return false;
22         if (p.val != q.val)
23             return false;
24         return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
25     }
26 }

 

相关题目

100. Same Tree

572. Subtree of Another Tree

LeetCode 题目总结

相关文章
相关标签/搜索