[leetcode]解决Same Tree的一点小心得
2017-10-12 22:04
429 查看
本次选择的题目是
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.
Solution:
首先我想到一个直接的方法,利用栈,按同样的顺序将p和q的各个节点push进去,再pop出来对比它们的val值,当然不是先全部push完再pop,而是先左再右,pop出来左节点,然后左节点一样了,push左节点的两个子节点,再pop出来右节点,检测右节点的val,push右节点的两个子节点,然后栈里还有左节点的两个子节点和右节点的两个子节点(假设它有,这里有4种情况,都没有,都有,都有左子节点,都有右子节点)一一对比。
discussion中提到的简单方法:
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.
Solution:
首先我想到一个直接的方法,利用栈,按同样的顺序将p和q的各个节点push进去,再pop出来对比它们的val值,当然不是先全部push完再pop,而是先左再右,pop出来左节点,然后左节点一样了,push左节点的两个子节点,再pop出来右节点,检测右节点的val,push右节点的两个子节点,然后栈里还有左节点的两个子节点和右节点的两个子节点(假设它有,这里有4种情况,都没有,都有,都有左子节点,都有右子节点)一一对比。
/** * 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; }else if(p != null && q != null){ Stack<TreeNode> stack1 = new Stack<TreeNode>(); Stack<TreeNode> stack2 = new Stack<TreeNode>(); stack1.push(p); stack2.push(q); while(!stack1.empty() && !stack2.empty()){ TreeNode temp1 = stack1.pop(); TreeNode temp2 = stack2.pop(); if(temp1.val!=temp2.val){ return false; } if(temp1.right!=null&&temp1.left!=null&&temp2.right!=null&&temp2.left!=null){ stack1.push(temp1.left); stack1.push(temp1.right); stack2.push(temp2.left); stack2.push(temp2.right); }else if(temp1.right!=null&&temp1.left==null&&temp2.right!=null&&temp2.left==null){ stack1.push(temp1.right); stack2.push(temp2.right); }else if(temp1.right==null&&temp1.left!=null&&temp2.right==null&&temp2.left!=null){ stack1.push(temp1.left); stack2.push(temp2.left); }else if(temp1.right==null&&temp1.left==null&&temp2.right==null&&temp2.left==null){ }else{ return false; } } return true; }else{ return false; } } }
discussion中提到的简单方法:
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 isSameTree(p.left, q.left) && isSameTree(p.right, q.right); return false; }
相关文章推荐
- [leetcode]解决Move Zeroes的一点小心得
- [leetcode]解决Burst Balloons的一点小心得
- [leetcode]解决Majority Element的一点小心得
- [leetcode]解决Clone Graph的一点小心得
- [leetcode]解决Climbing Stairs的一点小心得
- [leetcode]解决House Robber的一点小心得
- [leetcode]解决Kth Largest Element in an Array的一点小心得
- [leetcode]解决Minimum Height Trees的一点小心得
- [leetcode]解决Symmetric Tree的一点小心得
- [leetcode]解决Search a 2D Matrix II的一点小心得
- [leetcode]解决Assign Cookies的一点小心得
- [leetcode]解决Maximum Subarray的一点小心得
- 解决Dynamips使用时CPU占用率100%的一点个人心得
- 系统很慢一点解决心得
- 解决堆损坏的一点心得
- 关于信号槽连接地方的一点心得,一个问题困扰了一下午才解决,纪念一下。
- CGAL配置的一点心得(各种错误的解决办法)
- Executors.newFixedThreadPool和ArrayBlockingQueue一点使用心得
- 调试VC++程序的一点小心得
- Qml 一点心得