代码随想录打卡Day13

Leetcode 110

题目链接:平衡二叉树
对于其中的暗藏的后序遍历有了更深的了解

public boolean isBalanced(TreeNode root) {
        if(root==null) return true;
        int leftLength = getLength(root.left); // 左
        int rightLength = getLength(root.right); // 右
        if(Math.abs(leftLength-rightLength)>=2) return false; //中

        return isBalanced(root.left)&&isBalanced(root.right);
    }
    public int getLength(TreeNode root){
        if(root==null) return 0;
        return Math.max(getLength(root.left), getLength(root.right))+1;
    }

Leetcode 257

题目链接:二叉树的所有路径
着重注意题干中出现的关键词:叶子节点,要加上相应的条件判断

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new LinkedList<>();
        StringBuilder curPath = new StringBuilder();
        curPath.append(root.val);
        path(result, curPath, root);
        return result;
    }

    public void path(List<String> result, StringBuilder curPath, TreeNode cur){

        // 题干中有叶子节点,这种关键字,所以就要条件反射到这样写
        if(cur.left==null&&cur.right==null){
            result.add(curPath.toString());
            return;
        }
        int curCount = curPath.length();
        if(cur.left!=null){
            curPath.append("->").append(cur.left.val);
            path(result, curPath, cur.left);
            curPath.delete(curCount, curPath.length());
        }
        if(cur.right!=null){
            curPath.append("->").append(cur.right.val);
            path(result, curPath, cur.right);
            curPath.delete(curCount, curPath.length());
        }
        
    }
}

Leetcode 404:

题目链接:左叶子之和
依然是题目中的关键字:左叶子

    public int sumOfLeftLeaves(TreeNode root) {
        if(root==null) return 0;
        if(root.left!=null&&isLeaf(root.left)){
            return root.left.val+sumOfLeftLeaves(root.right);
        }
        if(root.left==null){
            return sumOfLeftLeaves(root.right);
        }
        return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
    }

    public boolean isLeaf(TreeNode node){
        if(node.left==null&&node.right==null) return true;
        else return false;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容