剑指Offer之Java算法习题精讲二叉树与N叉树

题目一

剑指Offer之Java算法习题精讲二叉树与N叉树_第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 {
    StringBuffer sb = new StringBuffer();
    List list = new ArrayList();
    public List binaryTreePaths(TreeNode root) {
        method(root);
        return list;
    }
    public void method(TreeNode root){
        if(root==null) return;
        int t = sb.length();
        sb.append(root.val);
        if(root.left==null&&root.right==null){
            list.add(sb.toString());
        }
        sb.append("->");
        method(root.left);
        method(root.right);
        sb.delete(t, sb.length());
    }
}

题目二

剑指Offer之Java算法习题精讲二叉树与N叉树_第2张图片

 解法

/**
 * 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 ans = 0;
    public int sumOfLeftLeaves(TreeNode root) {
        method(root,false);
        return ans;
    }
    public void method(TreeNode root,boolean flag){
        if(root==null) return;
        if(root.left==null&&root.right==null&&flag){
            ans+=root.val;
            return;
        }
        method(root.left,true);
        method(root.right,false);
    }
}

题目三

剑指Offer之Java算法习题精讲二叉树与N叉树_第3张图片

 解法

/*
// Definition for a Node.
class Node {
    public int val;
    public List children;
    public Node() {}
    public Node(int _val) {
        val = _val;
    }
    public Node(int _val, List _children) {
        val = _val;
        children = _children;
    }
};
*/
 
class Solution {
    public int maxDepth(Node root) {
        if(root==null){
            return 0;
        }
        int maxChildDepth = 0;
        for(int i = 0;i 
 

到此这篇关于剑指Offer之Java算法习题精讲二叉树与N叉树的文章就介绍到这了,更多相关 Java 二叉树内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(剑指Offer之Java算法习题精讲二叉树与N叉树)