226.翻转二叉树
思路
后续遍历,交换左右节点
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null) return root;
invertTree(root.left);
invertTree(root.right);
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
return root;
}
}
101. 对称二叉树
思路
前序遍历,分成左右两个子树,左子树向左的时候右子树向右,左子树向右的时候右子树向左
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return charge(root.left,root.right);
}
public boolean charge(TreeNode left,TreeNode right){
if(left==null&&right==null) return true;
if(left==null&&right!=null) return false;
if(left!=null&&right==null) return false;
if(left.val!=right.val) return false;
boolean outcharge=charge(left.left,right.right);
boolean incharge=charge(left.right,right.left);
return outcharge && incharge;
}
}
104.二叉树的最大深度
思路
层序遍历(递归迭代都行)
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
int leftdepth=maxDepth(root.left);
int rightdepth=maxDepth(root.right);
return Math.max(leftdepth,rightdepth)+1;
}
}
111.二叉树的最小深度
思路
后序遍历,从下往上获取该节点的最小高度,到最后即root的最小深度。这里是到叶子节点的最小深度,递归的终止条件要做限制
代码
class Solution {
public String removeDuplicates(String s) {
Stack<Character> stack=new Stack<>();
for(int i=s.length()-1;i>=0;i--){
char c=s.charAt(i);
if(!stack.isEmpty()){
if(c==stack.peek()){
stack.pop();
}else{
stack.push(c);
}
}else{
stack.push(c);
}
}
String result="";
while(!stack.isEmpty()){
result+=stack.pop();
}
return result;
}
}