平衡二叉树
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
if(Math.abs(cal(root.left)-cal(root.right))>1)
{
return false;
}
return isBalanced(root.left)&&isBalanced(root.right);
}
public int cal(TreeNode root)
{
if(root==null) return 0;
return Math.max(cal(root.left)+1,cal(root.right)+1);
}
}
二叉树最底层最左边的值
class Solution {
public int findBottomLeftValue(TreeNode root) {
if(root==null) return 0;
List<List<Integer>> sum=level(root);
int t=0;
for(List<Integer> x : sum)
{
for(int y : x)
{
t=y;
return y;
}
}
return t;
}
public List<List<Integer>> level(TreeNode root)
{
List<List<Integer>> sum=new LinkedList<>();
if(root==null) return sum;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty())
{
TreeNode temp;
List<Integer> x=new ArrayList<>();
int t=queue.size();
for(int i=0;i<t;i++)
{
temp=queue.poll();
x.add(temp.val);
if(temp.left!=null) queue.add(temp.left);
if(temp.right!=null) queue.add(temp.right);
}
sum.add(x);
}
Collections.reverse(sum);
return sum;
}
}
二叉树的右侧视图
class Solution {
List<Integer> x=new LinkedList<>();
public List<Integer> rightSideView(TreeNode root) {
if(root==null) return x;
List<List<Integer>> sum=level(root);
int y=0;
for(List<Integer> m : sum)
{
for(int n : m)
{
y=n;
}
x.add(y);
}
return x;
}
public List<List<Integer>> level(TreeNode root)
{
List<List<Integer>> sum=new LinkedList<>();
if(root==null) return sum;
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while(!queue.isEmpty())
{
List<Integer> x=new LinkedList<>();
TreeNode temp;
int t=queue.size();
for(int i=0;i<t;i++)
{
temp=queue.poll();
x.add(temp.val);
if(temp.left!=null) queue.add(temp.left);
if(temp.right!=null) queue.add(temp.right);
}
sum.add(x);
}
return sum;
}
}
二叉树剪枝
class Solution {
public TreeNode pruneTree(TreeNode root) {
if(root==null) return root;
root.left=pruneTree(root.left);
root.right=pruneTree(root.right);
if(root.val == 0 && root.left == null && root.right == null) return null;
return root;
}
}
从根节点到叶节点的路径之和
class Solution {
int k=0;
int res=0;
public int sumNumbers(TreeNode root) {
if(root==null) return 0;
cal(root,k);
return res;
}
public void cal(TreeNode root,int val)
{
if(root==null) return;
int k=val*10+root.val;
if(root.left==null&&root.right==null){
res=res+k;
return;
}
cal(root.left,k);
cal(root.right,k);
}
}
2021-09-07
最新推荐文章于 2024-05-20 18:16:07 发布