您的位置:首页 > 编程语言 > Java开发

[Java语言] Same Tree Symmetric Tree 相同树 对称树

2016-03-19 17:33 429 查看
Same Tree

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.
递归法 复杂度

时间 O(N) 空间 O(h) 递归栈空间
思路

如果两个根节点一个为空,一个不为空,或者两个根节点值不同,说明出现了不一样的地方,返回假。如果两个节点都是空,则是一样的,返回真。然后我们再递归它们的左右节点,如果递归结果中一个或两个是假,就返回假。否则,说明左右子树都是完全一样的。
代码

public class Solution {

public boolean isSameTree(TreeNode p, TreeNode q) {

if(p == null && q == null) return true;

if(p == null || q == null || p.val != q.val) return false;

return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);

}http://www.nvzi91.cn/jiankang/29958.html

}

复制代码
Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

1

/ \

2 2

/ \ / \

3 4 4 3

复制代码

But the following is not:

1

/ \

2 2

\ \

3 3

复制代码
递归法 复杂度

时间 O(N) 空间 O(h) 递归栈空间
思路

其实和Same Tree写法是一样的,Same Tree是比较两个节点的两个左边,然后再比较两个节点的两个右边。而对称树是要判断左节点的左节点和右节点的右节点相同(外侧),左节点的右节点和右节点的左节点相同(内侧)。不过对称树是判断一棵树,我们要用Same Tree一样的写法,就要另写一个可以比较两个节点的函数。
代码

public class Solution {

public boolean isSymmetric(TreeNode root) {

return root == null ? true : helper(root.left, root.right);

}http://www.nvzi91.cn/gongjingmilan/29959.html 

private boolean helper(TreeNode node1, TreeNode node2){

if(node1 == null && node2 == null){

return true;

}http://www.nvzi91.cn/gongjingyan/29960.html

if(node1 == null || node2 == null || node1.val != node2.val){

return false;

}

return helper(node1.left, node2.right) && helper(node1.right, node2.left);

}http://www.nvzi91.cn/gongwaiyun/29961.html

}

复制代码
迭代法 复杂度

时间 O(N) 空间 O(h)
思路

因为该题本质就是二叉树遍历,所以我们也可以用迭代来解。这里用一个队列,两棵树按照对称的顺序加入节点,然后进行比较。
代码

public class Solution {

public boolean isSymmetric(TreeNode root) {

if(root == null) return true;

Queue<TreeNode> queue1 = new LinkedList<TreeNode>();

Queue<TreeNode> queue2 = new LinkedList<TreeNode>();

queue1.offer(root.left);

queue2.offer(root.right);

while(!queue1.isEmpty() && !queue2.isEmpty()){

TreeNode node1 = queue1.poll();

TreeNode node2 = queue2.poll();

// 如果都是null,说明是相同的

if(node1 == null && node2 == null){

continue;

}http://www.nvzi91.cn/fujianyan/29962.html

// 如果有一个是null,或者值不同,则有问题

if(node1 == null || node2 == null || node1.val != node2.val){

return false;

}

queue1.offer(node1.left);

queue2.offer(node2.right);

queue1.offer(node1.right);

queue2.offer(node2.left);

}www.nvzi91.cn

return queue1.isEmpty() && queue2.isEmpty();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: