算法总结 - 树 - 递归

这篇博客总结了递归在处理二叉树问题中的应用,包括查找二叉树的最低公共祖先(LCA)、边界遍历以及验证二叉搜索树。递归解法详细阐述,覆盖了不同场景下的处理策略,如从根节点到最左节点的左边界,叶节点,再到最右节点的右边界,以及二叉搜索树的验证。
摘要由CSDN通过智能技术生成

Recursion (递归)

1. 普通二叉树

Lowest Common Ancestor of a Binary Tree

236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.


题目大意
给一个二叉树和两个节点,找他们最低的的公共祖先(离两个节点最近的公共父节点)。

解题思路
递归解法:

  1. 递归变量: 根节点,第一个子节点,第二个子节点

  2. 处理当前节点:
    a. 如果当前节点为null,等于第一个子节点,等于第二个节点,那么返回当前节点。
    b. 如果左子树公共节点与右子树公共节点都为null,证明公共节点为根节点即当前节点,否则那个公共节点不为空就返回哪个。

  3. 处理子节点:从左右子树分别找跟定两个子节点的最低公共节点。

复杂度
TC: O(n) SC: O(lgn)

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q) {
        return root;
    }
    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);
    if (left != null && right != null) {
        return root;
    } 
    return left != null ? left : right;
}

相似题目
116. Populating Next Right Pointers in Each Node
814. Binary Tree Pruning
701. Insert into a Binary Search Tree
111. Minimum Depth of Binary Tree
110. Balanced Binary Tree
572. Subtree of Another Tree
101. Symmetric Tree
563. Binary Tree Tilt
100. Same Tree
226. Invert Binary Tree
617. Merge Two Binary Trees


Boundary of Binary Tree

545. Boundary of Binary Tree
Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate nodes.

Left boundary is defined as the path from root to the left-most node. Right boundary is defined as the path from root to the right-most node. If the root doesn’t have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees.

The left-most node is defined as a leaf node you could reach when you always firstly travel to the left subtree if exists. If not, travel to the right subtree. Repeat until you reach a leaf node.

The right-most node is also defined by the same way with left and right exchanged.

Example 1
Input:

  1
   \
    2
   / \
  3   4

Ouput:
[1, 3, 4, 2]

Explanation:
The root doesn’t have left subtree, so the root itself is left boundary.
The leaves are node 3 and 4.
The right boundary are node 1,2,4. Note the anti-clockwise direction means you should output reversed right boundary.
So order them in anti-clockwise without duplicates and we have [1,3,4,2].
Example 2
Input:

    ____1_____
   /          \
  2            3
 / \          / 
4   5        6   
   / \      / \
  7   8    9  10  

Ouput:
[1,2,4,7,8,9,10,6,3]\

Explanation:
The left boundary are node 1,2,4. (4 is the left-most node according to definition)
The leaves are node 4,7,8,9,10.
The right boundary are node 1,3,6,10. (10 is the right-most node).
So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3].


题目大意
给一个二叉树,要求以逆时针的顺序来输出树的边界,按顺序分别为左边界,叶结点和右边界。

解题思路
递归解法:

  1. 递归变量: lb(遍历左边界), rb(遍历右边界), node(当前节点), res(存放边界节点)

  2. 处理当前节点:
    a. 如果当前节点为null返回。
    b. 如果lb,rb或当前节点是子节点则加入当前节点到res

  3. 处理子节点:从左右节点开始检查并打印边界。 以左节点为例,如果lb必然打印左节点,如果rb但是右节点为空则也需要打印左节点。

复杂度
TC: O(n) SC: O(1)

public List<Integer> boundaryOfBinaryTree(TreeNode root) {
    List<Integer> res = new ArrayList<Integer>();
    if (root != null) {
        res.add(root.val);
        getBounds(root.left, res, true, false);
        getBounds(root.right, res, false, true);
    }
    return res;
}


private void getBounds(TreeNode node, List<Integer> res, boolean lb, boolean rb) {
    if (node == null) return;
    if (lb) res.add(node.val);
    if (!lb && !rb && node.left == null && node.right == null) res.add(node.val);
    getBounds(node.left, res, lb, rb && node.right == null);
    getBounds(node.right, res, lb && node.left == null, rb);
    if (rb) res.add(node.val);
}

366. Find Leaves of Binary Tree
Given a binary tree, collect a tree’s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

Example:

Input: [1,2,3,4,5]

      1
     / \
    2   3
   / \     
  4   5    

Output: [[4,5,3],[2],[1]]

Explanation:

  1. Removing the leaves [4,5,3] would result in this tree:
   1
  / 
 2          
  1. Now removing the leaf [2] would result in this tree:
1          
  1. Now removing the leaf [1] would result in the empty tree:
[]         

题目大意
给一个二叉树,依次移除所有的子节点,返回每次移除的子节点。

解题思路
递归解法:

  1. 递归变量: 当前节点,存节点的res。

  2. 处理当前节点:
    a. 如果当前节点为null返回高度height为 -1。
    b. 根据左右节点得到当前节点的height,在res中根据当前节点的height加入到相应的list中。

  3. 处理子节点:移除左右子树的叶节点。
    4.返回:当前节点的高度height。

复杂度
TC: O(n) SC: O(n)

private List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> findLeaves(TreeNode root) {
    helper(root);
    return res;
}
private int helper(TreeNode node){
    if(null==node)  return -1;
    int height= 1 + Math.max(helper(node.left), helper(node.right));
    if(res.size()<height+1)  res.add(new ArrayList<Integer>());
    res.get(height).add(node.val);
    return height;
}

2. 二叉搜索树

Validate Binary Search Tree

98. Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.
Example 1:

    2
   / \
  1   3

Input: [2,1,3]
Output: true
Example 2:

    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node’s value is 5 but its right child’s value is 4.


题目大意
给一个二叉树,判断这是否是一个二叉搜索树。

解题思路
根据二叉搜索树的性质左子树的最大值小于根节点的值,右子树的最小值大于根节点的值,我们要用遍历记录当前子树的最小值和最大值确保没有子树违反这个规则。
递归解法:

  1. 处理当前节点:
    a. 如果当前节点为null返回true。
    b. 如果当前节点的值小于变量最小值或者大于变量最大值返回false。

  2. 处理子节点:检查左右子树是否是二叉搜索树

  3. 如果之前的检查都没有fail,则返回true

复杂度
TC: O(n) SC: O(n)

public boolean isValidBST(TreeNode root) {
    if (root == null) return true;
    return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

public boolean helper(TreeNode root, long min, long max){
    if (root.val <= min || root.val >= max){
        return false;
    }
    
    if(root.left != null && !helper(root.left, min, root.val)) return false;
    if (root.right != null && !helper(root.right, root.val, max)) return false;
    return true;
}

相似题目
450. Delete Node in a BST
655. Print Binary Tree
235. Lowest Common Ancestor of a Binary Search Tree
669. Trim a Binary Search Tree
700. Search in a Binary Search Tree


3. 多叉树

Kill Process

582. Kill Process
Given n processes, each process has a unique PID (process id) and its PPID (parent process id).

Each process only has one parent process, but may have one or more children processes. This is just like a tree structure. Only one process has PPID that is 0, which means this process has no parent process. All the PIDs will be distinct positive integers.

We use two list of integers to represent a list of processes, where the first list contains PID for each process and the second list contains the corresponding PPID.

Now given the two lists, and a PID representing a process you want to kill, return a list of PIDs of processes that will be killed in the end. You should assume that when a process is killed, all its children processes will be killed. No order is required for the final answer.

Example 1:

Input:
pid = [1, 3, 10, 5]
ppid = [3, 0, 5, 3]
kill = 5
Output: [5,10]
Explanation:
3
/
1 5
/
10
Kill 5 will also kill 10.

Note:

The given kill id is guaranteed to be one of the given PIDs.
n >= 1.


题目大意
给两个数组,一个是进程的数组,还有一个是进程数组中的每个进程的父进程组成的数组。另外给一个需要关闭的process id,返回要关闭这个process所需关闭的所有相关进程。

解题思路
用map来存所有的进程的关系,key为process id,value为子进程id。要关闭一个进程时,递归的关闭它所有的子进程。

复杂度
TC: O(n) SC: O(n)

public List < Integer > killProcess(List < Integer > pid, List < Integer > ppid, int kill) {
    HashMap < Integer, List < Integer >> map = new HashMap < > ();
    for (int i = 0; i < ppid.size(); i++) {
        if (ppid.get(i) > 0) {
            List < Integer > l = map.getOrDefault(ppid.get(i), new ArrayList < Integer > ());
            l.add(pid.get(i));
            map.put(ppid.get(i), l);
        }
    }
    Queue < Integer > queue = new LinkedList < > ();
    List < Integer > l = new ArrayList < > ();
    queue.add(kill);
    while (!queue.isEmpty()) {
        int r = queue.remove();
        l.add(r);
        if (map.containsKey(r))
            for (int id: map.get(r))
                queue.add(id);
    }
    return l;
}

相似题目
559. Maximum Depth of N-ary Tree


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值