【牛客剑指day04】

JZ55 二叉树的深度 ⭐

直接上代码

public class Solution {
    public int TreeDepth(TreeNode root) {
        if (root == null) return 0;
        else {
            return 1+Math.max(TreeDepth(root.left),TreeDepth(root.right));
        }
    }
}

JZ77 按之字形顺序打印二叉树 ⭐⭐

 思路1

public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        depth(pRoot,1,res);
        for (int i = 1; i < res.size(); i+=2) {
                Collections.reverse(res.get(i));
        }
        return res;
    }
 
    private void depth(TreeNode root,int d,ArrayList<ArrayList<Integer>> list){
        if(root==null) return;
        if(d>list.size()){
            list.add(new ArrayList<Integer>());
        }
        list.get(d-1).add(root.val);
        depth(root.left,d+1,list);
        depth(root.right,d+1,list);
    }
}

思路2

public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        LinkedList<TreeNode> qu = new LinkedList<>();
        if (pRoot != null) {
            qu.offer(pRoot);
        }
        int row = 1;
        while (!qu.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = qu.size(); i > 0; i--) {
                TreeNode t = qu.removeFirst(); //头出
                list.add(t.val);
                if (t.left != null) { //尾入
                    qu.addLast(t.left);
                }
                if (t.right != null) {
                    qu.addLast(t.right);
                }
            }
            if (row % 2 == 0) {
                Collections.reverse(list);
                ans.add(list);
            } else {
                ans.add(list);
            }
            row++;
        }
        return ans;
    }
}

JZ54 二叉搜索树的第k个节点 ⭐⭐


public class Solution {
    ArrayList<Integer> ans = new ArrayList<>();
    public int KthNode (TreeNode proot, int k) {
        if (proot == null || k == 0) return -1;
        inorder(proot);
        Collections.sort(ans);
        return ans.size() >= k ? ans.get(k - 1) : -1;
    }
    public void inorder(TreeNode proot) {
        if (proot != null) {
            inorder(proot.left);
            ans.add(proot.val);
            inorder(proot.right);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值