2024年7月17日
平衡二叉树
/**
* 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 isBalanced(TreeNode root) {
if(digui(root)==1){
return true;
}else{
return false;
}
}
public int digui(TreeNode root){
if(root==null){
return 1;
}
int h1 = height(root.left);
int h2 = height(root.right);
if(Math.abs(h1-h2)>1){
return 0;
}else{
return digui(root.left)*digui(root.right);
}
}
public int height(TreeNode root){
int height=1;
if(root==null){
return 0;
}else{
return Math.max(he(root.left,height),he(root.right,height));
}
}
public int he(TreeNode root, int height){
if(root!=null){
height+=1;
return Math.max(he(root.left,height),he(root.right,height));
}else{
return height;
}
}
}
题257. 二叉树的所有路径
涉及回溯,所以把路径记录设置为类成员,这样就不用反复传递了。
import java.util.*;
class Solution {
Vector<Integer> vec;
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<>();
vec = new Vector<>();
vec.add(root.val);
if(root.left==null&& root.right==null){
list.add(""+root.val);
return list;
}
if(root.left!=null){
list = digui(root.left,list);
}
if(root.right!=null){
list = digui(root.right,list);
}
return list;
}
public List<String> digui(TreeNode root,List<String> list){
vec.add(root.val);
if(root.left==null && root.right==null){
String res1 = "";
for(int i=0;i<vec.size()-1;i++){
res1+=vec.get(i);
res1+="->";
}
res1+=vec.get(vec.size()-1);
list.add(res1);
}else{
if(root.left!=null){
list = digui(root.left,list);
}
if(root.right!=null){
list = digui(root.right,list);
}
}
vec.remove(vec.size()-1);
return list;
}
}
题404. 左叶子之和
用一个标志位来记录当前节点是左子还是右子,如果是左子,就再判断是不是叶子节点,如果是才加上值。
class Solution {
int sum;
public int sumOfLeftLeaves(TreeNode root) {
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 0;
}
sum=0;
if(root.left!=null){
digui(root.left,1);
}
if(root.right!=null){
digui(root.right,0);
}
return sum;
}
public void digui(TreeNode root,int bool){
if(root.left==null && root.right==null && bool==1){
sum+=root.val;
return;
}
if(root.left!=null){
digui(root.left,1);
}
if(root.right!=null){
digui(root.right,0);
}
return;
}
}
标签:right,15,TreeNode,随想录,二叉树,return,null,root,left
From: https://www.cnblogs.com/hailicy/p/18314726