leetcode-二叉树总结

此文总结一下leetcode二叉树部分的常见题型和知识点:

常用知识点整理:

1. 树的深度和高度:

树的深度是从根节点开始往叶子结点算,而树的高度是从叶子结点往根结点算。

2. 树的遍历的迭代写法:

树的遍历分为先/中/后序三种,递归写法较为简单,这里简单介绍一下迭代写法的套路。

迭代写法简单来说就是使用栈来模拟迭代的过程,但是对于需要当前需要遍历到的元素,我们在这个元素前加入一个null作为标记,代码如下:

144. 二叉树的前序遍历 - 力扣(LeetCode)为例:

/**
 * 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<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        if(root == null) return res;
        stack.push(root);
        while(!stack.isEmpty()){
            //这里必须要pop操作,否则cur代表的节点会两次入栈,造成死循环
            TreeNode cur = stack.pop();
            if(cur != null){
                //由于栈FILO的特性,入栈的顺序和平时写递归法的顺序要反过来
                if(cur.right != null) stack.push(cur.right);
                if(cur.left != null) stack.push(cur.left);
                stack.push(cur);
                stack.push(null);
            }
            else{
                res.add(stack.pop().val);
            }
        }
        return res;
    }
}

3. 树的遍历与深度/高度的关联:

由于树的深度是从根节点往叶子结点开始计算,因此可以通过先序遍历来求得一颗二叉树的深度:

class Solution {
  /**
   * 递归法(求深度法)
   */
    //定义最大深度
    int maxnum = 0;

    public int maxDepth(TreeNode root) {
        ans(root,0);
        return maxnum;
    }
    
    //递归求解最大深度
    void ans(TreeNode tr,int tmp){
        if(tr==null) return;
        tmp++;
        maxnum = maxnum<tmp?tmp:maxnum;
        ans(tr.left,tmp);
        ans(tr.right,tmp);
        tmp--;
    }
}

 

同理,由于树的高度是从叶子结点往根节点算,所以可以采用后序遍历计算二叉树的高度。(虽然我们可以像上面一样,设置一个height的全局变量,但是这样写起来略微麻烦,更好的办法是二分):

class solution {
    /**
     * 递归法
     */
    public int maxHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = maxHeight(root.left);
        int rightHeight = maxHeight(root.right);
        return Math.max(leftHeight, rightHeight) + 1;
    }
}

 

posted @ 2023-10-24 21:40  Vege_dog  阅读(29)  评论(0)    收藏  举报