Easy 101题 Symmetric Tree
来源:互联网 发布:php 私有方法 编辑:程序博客网 时间:2024/05/17 01:21
Question:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Solution:
/** * 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 isSymmetric(TreeNode root) { if(root==null) return true; return isSymmetric(root.left,root.right); } public boolean isSymmetric(TreeNode left,TreeNode right){ if(left==null||right==null) return right==left; if(left.val!=right.val) return false; return isSymmetric(left.left,right.right)&&isSymmetric(left.right,right.left); } }
STACK做法
/** * 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 isSymmetric(TreeNode root) { if(root==null) return true; if((root.left==null&&root.right!=null)||(root.left!=null&&root.right==null)) return false; if(root.left==null&&root.right==null) return true; Stack<TreeNode> s=new Stack<TreeNode>(); s.push(root.left); s.push(root.right); while(!s.isEmpty()) { if(s.size()%2!=0) return false; TreeNode right = s.pop(); TreeNode left = s.pop(); if(right.val!=left.val) return false; if((left.left==null&&right.right!=null)||(left.left!=null&&right.right==null)) { return false; } if(!(left.left==null&&right.right==null)) { s.push(left.left); s.push(right.right); } if((right.left==null&&left.right!=null)||(right.left!=null&&left.right==null)) { return false; } if(!(right.left==null&&left.right==null)) { s.push(right.left); s.push(left.right); } } return true; } }
0 0
- Easy 101题 Symmetric Tree
- [Leetcode 101, Easy] Symmetric Tree
- LeetCode #101 - Symmetric Tree - Easy
- 【Leetcode-Easy-101】 Symmetric Tree
- Easy 21 Symmetric Tree(101)
- Symmetric Tree----easy
- Symmetric Tree(easy)
- 101. Symmetric Tree [easy] (Python)
- Easy-题目25:101. Symmetric Tree
- Leetcode 101. Symmetric Tree (Easy) (cpp)
- LeetCode解题报告 101. Symmetric Tree [easy]
- LeetCode-Easy刷题(20) Symmetric Tree
- leetcode 第101题 Symmetric tree
- LeetCode(101)Symmetric Tree
- LeetCode 101 Symmetric Tree
- LeetCode: Symmetric Tree [101]
- [leetcode 101] Symmetric Tree
- [LeetCode 101]Symmetric Tree
- Android 笔记 设定/sharedPreference
- Python1--糗事百科笑话爬取
- Reverse LinkedList
- Reverse Linked List
- Integer Vulnerability
- Easy 101题 Symmetric Tree
- Node.js 文档v4.6.1翻译 (1) 断言测试 assert
- Python2--糗百图片下载
- Using Darshan On BlueWaters
- 浏览器兼容问题(实战干货)
- mac解决python连接MySQL,import MySQLdb后,出现no suitable image... but wrong architecture
- Python3--翻页
- 第十四章 个人渣翻译 spf13插件---NERDCommenter 使用教程
- Medium 277题 Find the Celebrity