代码随想录第十八天|● 513.找树左下角的值● 112. 路径总和 113.路径总和ii● 106.从中序与后序遍历序列构造二叉树 105.从前序与中序遍历序列构造二叉树

513.找树左下角的值

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

思路

本体迭代法属于模板题,递归法稍微有些麻烦

关键在于如何确定节点是 最底层、最左边;

递归法:

        ①最底层:只需要不断向下遍历,每当找到一个叶子节点,假设它所在的层为最底层,并利用一个maxdeep变量记录最大深度,result记录当前节点值,当找到其他叶子节点时,比较当前深度与最大深度,若当前深度更深,就更新maxdeep并记录新的节点值作为result,最后遍历完所有节点,就能找到最底层的叶子节点与对应值了;        

        ②最左边:保证左子树先于右子树进行遍历即可,所以本题前中后序均可,(因为不需要处理中间节点,只要保证左在右前即可)同时,在更新maxdeep时 要求deep > maxdeep 而不能等于。这样就可以保证结果节点是最左侧、最深的

迭代法:

更好做了,只需要反复保存每次循环pop出的第一个节点值即可。那么最后循环结束保留下来的就是最深层、最左边的节点的值了。

迭代

class Solution {
    public List<List<Integer>> resList = new ArrayList<>();
    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        while(!que.isEmpty()){
            int len = que.size();
            List<Integer> list = new ArrayList<>();
            for(int i = 0; i < len; i++){
                TreeNode node = que.poll();
                list.add(node.val);
                if(node.left != null) que.offer(node.left);
                if(node.right != null) que.offer(node.right);
            }
            resList.add(list);
        }
        return resList.get(resList.size()-1).get(0);
    }
}

递归

要找深度最大的叶子节点。

那么如何找最左边的呢?可以使用前序遍历(当然中序,后序都可以,因为本题没有 中间节点的处理逻辑,只要左优先就行),保证优先左边搜索,然后记录深度最大的叶子节点,此时就是树的最后一行最左边的值。

class Solution {
    //注意初始化最大深度为-1 或初始为0,传入的deep为1也可
    public int maxDepth = -1, res = 0;
    public int findBottomLeftValue(TreeNode root) {
        find(root, 0);
        return res;
    }
    public void find(TreeNode root, int deep){
        if(root.left == null && root.right == null){
            if(deep > maxDepth){
                maxDepth = deep;
                res = root.val;
            }
            return;
        }
        if(root.left != null){
            find(root.left, deep + 1); //回溯
        }
        if(root.right != null){
            find(root.right, deep + 1); //回溯
        }
    }
}

112. 路径总和

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。

叶子节点 是指没有子节点的节点。

思路

路径求和 需要从上往下,深度优先 前序遍历

(本题前中后序都可以,无所谓,因为中节点也没有处理逻辑)来遍历二叉树

同时,这道题也是一道回溯题。怎么辨别某道题是回溯题呢?主要看题目是否需要利用遍历路径上的某些信息(如节点值,节点值的和,深度值等路径信息)。此题要求从根到叶的节点值之和,因此需要用到回溯的思想。

递归

与之前类似,回溯藏在函数调用的参数中

递归函数什么时候需要返回值?什么时候不需要返回值?这里总结如下三点:

  • 如果需要搜索整棵二叉树且不用处理递归返回值,递归函数就不要返回值。(这种情况就是本文下半部分介绍的113.路径总和ii)
  • 如果需要搜索整棵二叉树且需要处理递归返回值,递归函数就需要返回值。 (这种情况我们在236. 二叉树的最近公共祖先 (opens new window)中介绍)
  • 如果要搜索其中一条符合条件的路径,那么递归一定需要返回值,因为遇到符合条件的路径了就要及时返回。(本题的情况)
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) return false;
        return judge(root,targetSum);
    }
    public boolean judge(TreeNode root, int targetSum){
        if(root == null){
            return false;
        }
        if(root.left == null && root.right == null){
            if(targetSum == root.val){
                return true;
            }
        }
        boolean j1 = judge(root.left, targetSum - root.val);
        boolean j2 = judge(root.right, targetSum - root.val);

        if(j1 == true || j2 == true){
            return true;
        }
        return false;
    }
}

迭代

利用栈进行迭代 问题在于 如何回溯 sum

录中解决方案是额外借助一个stack存放sum

class solution {
    public boolean haspathsum(treenode root, int targetsum) {
        if(root == null) return false;
        stack<treenode> stack1 = new stack<>();
        stack<integer> stack2 = new stack<>();
        stack1.push(root);
        stack2.push(root.val);
        while(!stack1.isempty()) {
            int size = stack1.size();

            for(int i = 0; i < size; i++) {
                treenode node = stack1.pop();
                int sum = stack2.pop();

                // 如果该节点是叶子节点了,同时该节点的路径数值等于sum,那么就返回true
                if(node.left == null && node.right == null && sum == targetsum) {
                    return true;
                }
                // 右节点,压进去一个节点的时候,将该节点的路径数值也记录下来
                if(node.right != null){
                    stack1.push(node.right);
                    stack2.push(sum + node.right.val);
                }
                // 左节点,压进去一个节点的时候,将该节点的路径数值也记录下来
                if(node.left != null) {
                    stack1.push(node.left);
                    stack2.push(sum + node.left.val);
                }
            }
        }
        return false;
    }
}

113. 路径之和 Ⅱ

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点.

递归1

列举了多种不同的写法,从中体会边界处理与递归的逻辑

class Solution {
    public List<List<Integer>> resList = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if(root == null){
            return resList;
        }
        List<Integer> list = new ArrayList<Integer>();
        getPath(root, targetSum, list);
        return resList;
    }
    public void getPath(TreeNode root, int targetSum, List<Integer> path){
        path.add(root.val);
        if(root.left == null && root.right == null){
            if(root.val == targetSum){
                resList.add(new ArrayList<Integer>(path));
            }
            return;
        }
        if(root.left != null){

            getPath(root.left, targetSum - root.val, path);
            path.remove(path.size()-1);
        }
        if(root.right != null){

            getPath(root.right, targetSum - root.val, path);
            path.remove(path.size()-1);
        }

    }
}

递归2

import java.util.ArrayList;
import java.util.List;

class Solution {
    private List<List<Integer>> result = new ArrayList<>();
    private List<Integer> path = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        result.clear();
        path.clear();
        if (root == null) return result;
        path.add(root.val);
        traversal(root, sum - root.val);
        return result;
    }

    private void traversal(TreeNode cur, int count) {
        if (cur.left == null && cur.right == null && count == 0) {
            result.add(new ArrayList<>(path));
            return;
        }

        if (cur.left == null && cur.right == null) return;

        if (cur.left != null) {
            path.add(cur.left.val);
            count -= cur.left.val;
            traversal(cur.left, count);
            count += cur.left.val;
            path.remove(path.size() - 1);
        }
        if (cur.right != null) {
            path.add(cur.right.val);
            count -= cur.right.val;
            traversal(cur.right, count);
            count += cur.right.val;
            path.remove(path.size() - 1);
        }
    }
}

递归3

class Solution {
    public List<List<Integer>> resList = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if(root == null){
            return resList;
        }
        List<Integer> list = new ArrayList<Integer>();
        list.add(root.val);
        getPath(root, targetSum, list);
        return resList;
    }
    public void getPath(TreeNode root, int targetSum, List<Integer> path){
        if(root.left == null && root.right == null){
            if(root.val == targetSum){
                resList.add(new ArrayList<Integer>(path));
            }
            return;
        }
        if(root.left != null){
            path.add(root.left.val);
            getPath(root.left, targetSum - root.val, path);
            path.remove(path.size()-1);
        }
        if(root.right != null){
            path.add(root.right.val);
            getPath(root.right, targetSum - root.val, path);
            path.remove(path.size()-1);
        }
    }
}

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

思路

首先明确做此类题目的方法,从前序数组中提取第一个元素,此为当前根节点,然后在中序数组里查找这个元素对应的下标,进而可以确定左、右子树节点的数量,递归地做下去即可

class Solution {
    public HashMap<Integer,Integer> map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map = new HashMap<>();
        for(int i=0; i < inorder.length; i++){
            map.put(inorder[i],i);
        }
        return buildByPreIn(preorder,0, preorder.length, inorder, 0, inorder.length);
    }
    public TreeNode buildByPreIn(int [] preorder, int pre1, int pre2, int [] inorder, int in1, int in2){
        //保持参数范围左闭右开
        if(pre1 >= pre2 || in1 >= in2){
            return null;
        }
        //找到前序遍历的第一个元素在 中序遍历中的 下标
        int rootIndex = map.get(preorder[pre1]);
        //构造root节点
        TreeNode root = new TreeNode(inorder[rootIndex]);
        //保存中序左子树个数,用于确定前序数列的个数
        int lenOfLeft = rootIndex - in1;
        //注意左闭右开,注意确定区间
        root.left = buildByPreIn(preorder,pre1 + 1, pre1 + lenOfLeft + 1,
                inorder, in1, rootIndex);
        root.right = buildByPreIn(preorder, pre1 + lenOfLeft + 1, pre2,
                inorder, rootIndex + 1, in2);
        return root;
    }
}

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

思路

与105基本一致,注意边界,分清区间

class Solution {
    HashMap<Integer, Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for(int i=0; i < inorder.length; i++){
            map.put(inorder[i],i);
        }
        return buidByInPos(inorder, 0, inorder.length, postorder, 0, postorder.length);
    }
    public TreeNode buidByInPos(int [] inorder, int in1, int in2, int [] postorder, int po1, int po2){
        if(in1 >= in2 || po1 >= po2){
            return null;
        }
        //获得当前树的root
        int rootIndex = map.get(postorder[po2-1]);
        //中左子树个数
        int lenOfLeft = rootIndex - in1;
        TreeNode root = new TreeNode(postorder[po2-1]);
        root.left = buidByInPos(inorder, in1, rootIndex,
                                postorder, po1, po1 + lenOfLeft);
        root.right = buidByInPos(inorder, rootIndex + 1, in2,
                                postorder,po1 + lenOfLeft, po2 - 1);
        return root;
    }
}

  • 10
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值