算法|找树左下角的值、路径总和、从中序与后序遍历序列构造二叉树、从前序与中序遍历序列构造二叉树

一、 513. 找树左下角的值

题目链接:https://leetcode.cn/problems/find-bottom-left-tree-value/
思路一:使用前序遍历,达到叶子节点,即root.left == null && root.right == null,根据深度depth更新最大的结果

/**
 * 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 {
    private int maxDepth = Integer.MIN_VALUE;
    private int result;
    private void findBottomLeftValue(TreeNode root, int depth){
        //到了叶子节点,更新结果
        if (root.left == null && root.right == null) {
            if (maxDepth < depth) {
                maxDepth = depth;
                result = root.val;
            }
            return;
        }
        if (root.left != null) {
            depth++;
            findBottomLeftValue(root.left, depth);
            depth--;
        }

        if (root.right != null) {
            depth++;
            findBottomLeftValue(root.right, depth);
            depth--;
        }
    }
    public int findBottomLeftValue(TreeNode root) {
        if (root == null) return 0;
        findBottomLeftValue(root, 0);
        return result;
    }
}

思路二:使用层序遍历,当 if (i == 0) 更新结果

/**
 * 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 findBottomLeftValue(TreeNode root) {
        if (root == null) return 0;
        int result = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.poll();
                if (i == 0) {
                    result = treeNode.val;
                }
                if (treeNode.left != null) queue.offer(treeNode.left);
                if (treeNode.right != null) queue.offer(treeNode.right);
            }
        }
        return result;
    }
}

二、112. 路径总和

题目链接:https://leetcode.cn/problems/path-sum/
思路一:使用前序遍历

/**
 * 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 hasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;
        if (root.left == null && root.right == null) {
            return targetSum == root.val;
        }

        if (root.left != null) {
            if (hasPathSum(root.left, targetSum - root.val)) return true;
        }
        if (root.right != null) {
            if (hasPathSum(root.right, targetSum - root.val)) return true;
        }
        return false;
    }
}

思路二、前序迭代法

/**
 * 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 hasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;
        Stack<TreeNode> stackNode = new Stack<>();
        stackNode.push(root);
        Stack<Integer> stackSum = new Stack<>();
        stackSum.push(root.val);
        while (!stackNode.isEmpty()) {
            TreeNode treeNode = stackNode.pop();
            int sum = stackSum.pop();
            if (treeNode.left == null && treeNode.right == null && targetSum == sum) return true;
            if (treeNode.right != null) {
                stackNode.push(treeNode.right);
                stackSum.push(sum + treeNode.right.val);
            }
            if (treeNode.left != null) {
                stackNode.push(treeNode.left);
                stackSum.push(sum + treeNode.left.val);
            }
        }
        return false;
    }
}

三、 113. 路径总和 II

题目链接:https://leetcode.cn/problems/path-sum-ii/
思路一:前序遍历,到达叶子节点即 root.left == null && root.right == null 判断是否符合条件,符合条件加入到结果集中

/**
 * 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 {
    private void pathSum(TreeNode root, int targetSum, List<Integer> paths, List<List<Integer>> result) {
        paths.add(root.val);
        if (root.left == null && root.right == null) {
            if (targetSum == root.val) {
                result.add(new ArrayList<Integer>(paths));
            }      
            return;
        }
        if (root.left != null) {
            pathSum(root.left, targetSum - root.val, paths, result);
            paths.remove(paths.size() - 1);
        }

        if (root.right != null) {
            pathSum(root.right, targetSum - root.val, paths, result);
            paths.remove(paths.size() - 1);
        }

    }
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<Integer> paths = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        pathSum(root, targetSum, paths, result);
        return result;
    }
}

思路二:使用两个栈,一个栈存放treeNode 一个栈放new Object[]{'节点值列表',‘到该节点的和’}

/**
 * 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<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        Stack<TreeNode> stackNode = new Stack<>();
        stackNode.push(root);
        Stack<Object[]> stackSum = new Stack<>();
        stackSum.push(new Object[] {root.val + "", root.val});
        while (!stackNode.isEmpty()) {
            TreeNode treeNode = stackNode.pop();
            Object  values[] = stackSum.pop();
            if (treeNode.left == null && treeNode.right == null) {
                //搜集结果
                if (targetSum == (int)values[1]) {
                    System.out.print(((String)values[0]));
                    System.out.println();
                    String paths[] = ((String)values[0]).split(",");
                    List<Integer> list = new ArrayList<>();
                    for (String path:paths) {
                        list.add(Integer.parseInt(path));
                    }
                    result.add(list);
                }
                continue;
            }
            if (treeNode.right != null) {
                stackNode.push(treeNode.right);
                stackSum.push(new Object[]{((String)values[0]) + "," + treeNode.right.val,  (int)values[1] + treeNode.right.val});
            }
            if (treeNode.left != null) {
                stackNode.push(treeNode.left);
                stackSum.push(new Object[]{((String)values[0]) + "," + treeNode.left.val, (int)values[1] + treeNode.left.val});
            }
        }
        return result;
    }
}

四、106. 从中序与后序遍历序列构造二叉树

/**
 * 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 {
    private HashMap<Integer, Integer> hashMap = new HashMap<>();
    private TreeNode buildTree(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
        if (inStart >= inEnd || postStart > postEnd) return null;
        //后序中最后一个元素,是中序的root
        int val = postorder[postEnd - 1];
        //在中序的切割点索引
        int inIndex = hashMap.get(val);
        //中序列表中分割点到inStart的差值,主要用于切割后序
        int inLeft = inIndex - inStart;
        TreeNode root = new TreeNode(val);
        root.left = buildTree(inorder, inStart, inIndex, postorder, postStart, postStart + inLeft);
        root.right = buildTree(inorder, inIndex + 1, inEnd, postorder, postStart + inLeft, postEnd - 1);
        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || postorder == null) return null;
        //把中序放到hashmap,便于查找
        for (int i = 0; i < inorder.length; i++) {
            hashMap.put(inorder[i], i);
        }
        return buildTree(inorder, 0, inorder.length, postorder, 0, postorder.length);
    }
}

五、 105. 从前序与中序遍历序列构造二叉树

题目链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

/**
 * 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 {
    private HashMap<Integer, Integer> hashMap;
    private TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
        if (preStart >= preEnd || inStart >= inEnd) return null;
        int val = preorder[preStart];
        int inIndex = hashMap.get(val);
        int leftIn = inIndex - inStart;
        TreeNode treeNode = new TreeNode(val);
        treeNode.left = buildTree(preorder, preStart + 1, preStart + leftIn + 1, inorder, inStart, inIndex);
        treeNode.right = buildTree(preorder, preStart + leftIn + 1, preEnd, inorder, inIndex + 1, inEnd);
        return treeNode;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null) return null;
        hashMap = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            hashMap.put(inorder[i], i);
        }
        return buildTree(preorder, 0, preorder.length, inorder, 0, inorder.length);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,189评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,577评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,857评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,703评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,705评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,620评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,995评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,656评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,898评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,639评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,720评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,395评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,982评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,953评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,195评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,907评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,472评论 2 342

推荐阅读更多精彩内容