100. Same Tree

Total Accepted: 127501 Total Submissions: 294584 Difficulty: Easy

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.

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
//递归调用,首先判断是否都是空,如果是,则返回true,否则若都不为空,则分两步
//走,如果根节点值相同,则看两者的左节点是否一样,再看右节点,若有不同,则返回false;
//还有就是其他情况:两树中有一树为空的情况,直接返回false
public class Solution {
public boolean isSameTree(TreeNode root1, TreeNode root2){
if(root1==null&&root2==null)
return true;
while(root1!=null&&root2!=null){
if(root1.val==root2.val){
return isSameTree(root1.left, root2.left)&&isSameTree(root1.right, root2.right);
}else{
return false;
}
}
return false;
}
}

101. 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

Note:
Bonus points if you could solve it both recursively and iteratively.

minimum-depth-of-binary-tree

题目描述

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

思路:与求二叉树的深度类似,求二叉树的深度,主要是求二叉树的最长路径,此处求二叉树的最短路径,思路如下:

  1.当root=null时,直接return 0;

  2.当root.left=null且root.right=null时,直接return 1;

  3.当root.left=null或者root.right=null时,递归调用(返回右子树最小长度)run(root.right)+1或(返回左子树最小长度)run(root.left)+1;

  4.最后root.left!=null且root.right!=null时,返回左子树和右子树的最小路径长度;

public class Solution {
public int run(TreeNode root) {
if(root==null)
return 0;
if(root.left==null&&root.right==null)
return 1;
if(root.left==null)
return run(root.right)+1;
if(root.right==null)
return run(root.left)+1;
return Math.min(run(root.left),run(root.right))+1;
}
}
binary-tree-postorder-traversal

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree{1,#,2,3},

   1
\
2
/
3

return[3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

考察二叉树的后序遍历:

非递归思路:使用栈来作为辅助

  思路一:stack作为缓冲,保存左右孩子节点,stack1作为最终保存结果;

    1.当root为空,直接返回空;

    2.当root不为空时,当root入栈stack,直接出栈stack,如果该节点没有左右孩子,直接将该节点入栈stack1,最后出栈;

    3.如果该节点有左右孩子,将其左右孩子依次入栈stack,保存访问过的节点,重复上面的过程,保证每次取栈顶的元素,左孩子在右孩子前面被访问,左孩子和右孩子都在根节点前面被访问。

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(root==null)
return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
stack.push(root);
while(!stack.empty()){
TreeNode curNode = stack.pop();
if(curNode.left!=null){
stack.push(curNode.left);
}
if(curNode.right!=null){
stack.push(curNode.right);
}
stack2.push(curNode);
}
while(!stack2.empty()){
list.add(stack2.pop().val);
}
return list;
} }

  思路二:对于任一结点P,将其入栈,然后沿其左子树一直往下搜索,直到搜索到没有左孩子的结点,此时该结点出现在栈顶,但是此时不能将其出栈并访问,因此其右孩子还为被访问。所以接下来按照相同的规则对其右子树进行相同的处理,当访问完其右孩子时,该结点又出现在栈顶,此时可以将其出栈并访问。这样就保证了正确的访问顺序。可以看出,在这个过程中,每个结点都两次出现在栈顶,只有在第二次出现在栈顶时,才能访问它。因此需要多设置一个变量标识该结点是否是第一次出现在栈顶。

递归思路:

  1.递归遍历左子树;

  2.递归遍历右子树;

  3.输出根节点;

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
postorderTraversalHelper(root,list);
return list;
}
public void postorderTraversalHelper(TreeNode root, ArrayList<Integer> list){
if(root==null)
return;
postorderTraversalHelper(root.left,list);
postorderTraversalHelper(root.right,list);
list.add(root.val);
}
}
binary-tree-preorder-traversal

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree{1,#,2,3},

   1
\
2
/
3

return[1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*; public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
preorderTraversalHelper(root, list);
return list;
}
public void preorderTraversalHelper(TreeNode root, ArrayList<Integer> list){
if(root==null)
return;
list.add(root.val);
preorderTraversalHelper(root.left,list);
preorderTraversalHelper(root.right,list);
}
}

LeetCode之二叉树作题java的更多相关文章

  1. LeetCode第[21][23]题(Java):Merge Sorted Lists

    题目:合并两个已排序链表 难度:Easy 题目内容: Merge two sorted linked lists and return it as a new list. The new list s ...

  2. LeetCode之数组处理题java

    342. Power of Four Total Accepted: 7302 Total Submissions: 21876 Difficulty: Easy Given an integer ( ...

  3. LeetCode之字符串处理题java

    344. Reverse String Write a function that takes a string as input and returns the string reversed. E ...

  4. LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2

    题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...

  5. LeetCode第[18]题(Java):4Sum 标签:Array

    题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...

  6. LeetCode第[1]题(Java):Two Sum 标签:Array

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  7. LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY

    题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...

  8. LeetCode第[29]题(Java):Divide Two Integers

    题目:两整数相除 难度:Medium 题目内容: Given two integers dividend and divisor, divide two integers without using ...

  9. Java实现 LeetCode 297 二叉树的序列化与反序列化

    297. 二叉树的序列化与反序列化 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得 ...

随机推荐

  1. 什么是API?我们常说调用API

    如果你不知道 API 是什么,说明你英语真的很差. API 就是 Application Programming Interface 三个单词,如果你不能顾名思义的话,我就举例说明. 1. DOM A ...

  2. 传智:自己简单实现一个struts2框架的demo

    struts2的结构图: 代码实现: 组织结构: 主要代码: package cn.itcast.config; import org.apache.log4j.Logger; import org. ...

  3. 通过VNC连接远程服务器,然后登陆服务器上的虚拟机,出现键盘输入问题的解决方法

    前几天由于要在服务器上装一个虚拟机,然后就选择了vmware workstation,装好之后,进入虚拟机中的centOS系统,发现键盘上的Cpas Lock键不起作用,按下之后还是输入小写,而且按住 ...

  4. JSP session过期时间(小记)

    以下情况,Session结束生命周期,Servlet容器将Session所占资源释放:1.客户端关闭浏览器2.Session过期3.服务器端调用了HttpSession的invalidate()方法. ...

  5. Robot Framework中使用HttpLibrary教程and中文支持

    Robot Framework中使用and转参数时,默认不支持中文模式,如图场景: 会出现这种错误 FAIL : UnicodeDecodeError: 'ascii' codec can't dec ...

  6. 取出表A中第31到第40记录

    方法一: select top 10 * from A where RowId not in (select top 10 RowId from A) 方法二(使用临时表): with tempTab ...

  7. [CF125E]MST Company

    codeforces description 给出一张\(n\)点\(m\)条边的无向图,求一棵满足\(1\)号点度数恰好为\(k\)的最小生成树,并输出方案. \(1\le k\le n\le500 ...

  8. streamsets geoip 使用

    geoip 分析对于网站数据分析是很方便的 安装geoip2 下载地址 https://dev.maxmind.com/geoip/geoip2/geolite2/ 配置streamsets geoi ...

  9. fb远程连接服务器调试,碉堡了

    开发中经常碰到本地代码没问题,上传到服务器上就有有问题, 这个时候调试变的很麻烦,放个textField自己保存日志这种方式调试的都是. 今天刚学了远程连接服务器,adobe真是牛逼坏了啊. 新增一个 ...

  10. bzoj2257瓶子和燃料

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2257 以两个瓶子为例,可以倒出它们的差,这是它们容量的gcd的倍数. k个瓶子就可以倒出它们 ...