[leetcode]100.Same Tree
阿新 • • 發佈:2018-10-02
link des truct mov binary 遍歷 bool lis lee
題目
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
解法一
思路
先序遍歷的遞歸
代碼
/** * 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) { if(p == null && q == null) return true; if(p == null || q == null) return false; if(p.val != q.val) return false; return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right); } }
解法二
思路
用棧或者隊列來實現層次遍歷,一個棧(隊列) 或者 兩個棧(隊列)都可以。如果用一個棧(隊列),那就是兩棵樹同一個位置的節點同時入棧,出棧的時候同時出棧,然後進行對比。以下用一個隊列實現。
代碼
/** * 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) { Deque<TreeNode> queue = new LinkedList<>(); queue.addLast(p); queue.addLast(q); while(!queue.isEmpty()){ p = queue.removeFirst(); q = queue.removeFirst(); if(p == null && q == null) continue; else if(p == null || q == null || q.val!=p.val) return false; else { queue.addLast(p.left); queue.addLast(q.left); queue.addLast(p.right); queue.addLast(q.right); } } return true; } }
[leetcode]100.Same Tree