代码随想录二刷day17

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

二叉树中深度指的是根节点到当前节点的节点个数, 二叉树中的高度指的是当前节点到叶子节点的节点个数
可以通前序遍历求深度
通过后序遍历求高度


一、力扣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 {
    int res;
    public int maxDepth(TreeNode root) {
        res = 0;
        if(root == null)return res;
        fun(root, 1);
        return res;
    }
    public void fun(TreeNode root, int cur){
        res = res > cur ? res : cur;
        if(root.left == null && root.right == null)return;
        if(root.left != null){
            fun(root.left, cur + 1);
        }
        if(root.right != null){
            fun(root.right, cur + 1);
        }
    }
}

二、力扣110. 平衡二叉树

递归

/**
 * 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) {
        return fun(root) != -1;
    }
    public int fun(TreeNode root){
        if(root == null)return 0;
        int leftHigh = fun(root.left);
        if(leftHigh == -1)return -1;
        int rightHigh = fun(root.right);
        if(rightHigh == -1)return -1;
        int res = 0;
        if(Math.abs(leftHigh - rightHigh) > 1){
            return -1;
        }else{
            return Math.max(leftHigh, rightHigh) + 1;
        }
    }
}

迭代

class Solution {
   /**
     * 迭代法,效率较低,计算高度时会重复遍历
     * 时间复杂度:O(n^2)
     */
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while (root!= null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            TreeNode inNode = stack.peek();
            // 右结点为null或已经遍历过
            if (inNode.right == null || inNode.right == pre) {
                // 比较左右子树的高度差,输出
                if (Math.abs(getHeight(inNode.left) - getHeight(inNode.right)) > 1) {
                    return false;
                }
                stack.pop();
                pre = inNode;
                root = null;// 当前结点下,没有要遍历的结点了
            } else {
                root = inNode.right;// 右结点还没遍历,遍历右结点
            }
        }
        return true;
    }

    /**
     * 层序遍历,求结点的高度
     */
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        int depth = 0;
        while (!deque.isEmpty()) {
            int size = deque.size();
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = deque.poll();
                if (poll.left != null) {
                    deque.offer(poll.left);
                }
                if (poll.right != null) {
                    deque.offer(poll.right);
                }
            }
        }
        return depth;
    }
}

三、力扣257. 二叉树的所有路径

递归

/**
 * 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 {
    List<String> res = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {
        List<Integer> li = new ArrayList<>();
        if(root == null)return res;
        fun(root, li);
        return res;
    }
    public void fun(TreeNode root, List<Integer> li){
        li.add(root.val);
        if(root.left == null && root.right == null){
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < li.size(); i ++){
                if(i != li.size()-1){
                    sb.append(li.get(i)).append("->");
                }else{
                    sb.append(li.get(i));
                }
            }
            res.add(sb.toString());
            return;
        }
        if(root.left != null){
            fun(root.left, li);
            li.remove(li.size()-1);
        }
        if(root.right != null){
            fun(root.right, li);
            li.remove(li.size()-1);
        } 
    }
}

迭代

/**
 * 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 List<String> binaryTreePaths(TreeNode root) {
        Deque<Object> deq = new LinkedList<>();
        List<String> res = new ArrayList<>();
        if(root == null)return res;
        deq.offerLast(root);
        deq.offerLast("" + root.val);
        while(!deq.isEmpty()){
            String path = (String)deq.pollLast();
            TreeNode cur = (TreeNode)deq.pollLast();
            if(cur.left == null && cur.right == null){
                res.add(path);
                continue;
            }
            if(cur.right != null){
                deq.offerLast(cur.right);
                deq.offerLast(path + "->" + cur.right.val);
            }
            if(cur.left != null){
                deq.offerLast(cur.left);
                deq.offerLast(path + "->" + cur.left.val);
            }
        }
        return res;
    }
}

四、力扣404. 左叶子之和

递归

/**
 * 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 sumOfLeftLeaves(TreeNode root) {
        if(root == null)return 0;
        int leftVal = 0, rightVal = 0;
        if(root.left != null){
            if(root.left.left == null && root.left.right == null){
                leftVal = root.left.val;
            }
        }
        leftVal += sumOfLeftLeaves(root.left);
        rightVal += sumOfLeftLeaves(root.right);
        return leftVal + rightVal;
    }
}

递归

/**
 * 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 sumOfLeftLeaves(TreeNode root) {
        Deque<TreeNode> deq = new LinkedList<>();
        int sum = 0;
        if(root == null)return sum;
        deq.offerLast(root);
        while(!deq.isEmpty()){
            int len = deq.size();
            for(int i = 0; i < len; i ++){
                TreeNode p = deq.pollFirst();
                if(p.left != null && p.left.left == null && p.left.right == null){
                    sum += p.left.val;
                }
                if(p.left != null)deq.offerLast(p.left);
                if(p.right != null)deq.offerLast(p.right);
            }
        }
        return sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乱世在摸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值