劍指offer java實現合集(13)第61~66題

61.二叉搜索樹的第K個節點

藉助二叉搜索樹的特性

import java.util.*;
public class Solution {
    ArrayList<TreeNode> res = new ArrayList();
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot==null){
            return null;
        }
        if(k==0){
            return null;
        }
        inorder(pRoot);
        if(k>res.size()){
            return null;
        }
            return res.get(k-1);
        
    }
    public void inorder(TreeNode root){
        if(root==null){
            return ;
        }
        if(root.left!=null){
            inorder(root.left);
        }
        res.add(root);
        if(root.right!=null){
            inorder(root.right);
        }
    }
}

66.機器人的運動範圍

public class Solution {


public int movingCount(int threshold, int rows, int cols) {
        boolean[][] visited = new boolean[rows][cols];
        return countingSteps(threshold,rows,cols,0,0,visited);
    }
    public int countingSteps(int limit,int rows,int cols,int r,int c,boolean[][] visited){
        if (r < 0 || r >= rows || c < 0 || c >= cols
                || visited[r][c] || bitSum(r) + bitSum(c) > limit)  return 0;
        visited[r][c] = true;
        return countingSteps(limit,rows,cols,r - 1,c,visited)
                + countingSteps(limit,rows,cols,r,c - 1,visited)
                + countingSteps(limit,rows,cols,r + 1,c,visited)
                + countingSteps(limit,rows,cols,r,c + 1,visited)
                + 1;
    }
    public int bitSum(int t){
        int count = 0;
        while (t != 0){
            count += t % 10;
            t /= 10;
        }
        return  count;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章