二叉树算法题总结

二叉树集训

一、二叉树的基础知识复习

前序遍历(根-左-右)

中序遍历(左-根-右)

后序遍历(左-右-根)

671. 二叉树中第二小的节点

​ 二叉树中寻找第二小的节点

​ 如果一个节点有两个子节点的话,那么该节点的值等于两个子节点中较小的一个。

		2
        / \
       2   5
          / \
         5   72
       /   \
      2     5
     / \   / \
    2   4 5   7 ;
提出问题:
	这种情况如何判断4是最小???
    dfs的条件如何设置??? 当val!=-1&& val >=res 就返回。       
     

1.朴素的DFS深搜二叉树

/**
 * 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 res;
    int min;

    public int findSecondMinimumValue(TreeNode root) {
        res = -1;
        min = root.val;
        dfs(root);
        return res;

    }

    public void dfs(TreeNode p){
        if(p==null) return;
        if(res!=-1&&p.val>=res){
            return;
        }
        if(p.val>min){
            res = p.val;
        }
        dfs(p.left);
        dfs(p.right);
    }
}

2.翻转二叉树

剑指 Offer 27. 二叉树的镜像

​ 非常经典的翻转二叉树。

例如输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
镜像输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /**
    递归思想
     */
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null){
            return null;
        }
        TreeNode left = mirrorTree(root.left);
        TreeNode right = mirrorTree(root.right);

        root.left = right;
        root.right = left;

        return root;

    }
}

3.判断对称

剑指 Offer 28. 对称的二叉树

​ 判断二叉树是否对称。

​ l.right == r.left && l.left == r.right。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {

        if(root==null) return true;

        return assertTree(root.right,root.left);

        

    }

    public boolean assertTree(TreeNode r,TreeNode l){
        if(r == null&& l == null) return true;

        if(r == null||l==null||r.val!=l.val) return false;

        return assertTree(r.right,l.left)&&assertTree(r.left,l.right);
    }
}

4.广度优先遍历bfs

剑指 Offer 32 - II. 从上到下打印二叉树 II

​ 经典的BFS使用,使用队列存放每一层的元素,并且按照记录的每一层元素的个数出队。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /**
    BFS循环,当队列为空时返回。

    queue.poll() 从队列头部删除一个元素,如果为空返回null
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res= new ArrayList<>();
        // 判断边界条件
        if(root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        
        queue.add(root);

        while(!queue.isEmpty()){
            //num表示该层的元素个数
            int num = queue.size();

            List<Integer> list = new ArrayList<>();
            for(int i =0;i<num;i++){
                //出队 并放到 list中
                TreeNode node = queue.poll();
                list.add(node.val);
                //循环将所有下层的左右子节点入队
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
            }
            res.add(list);
        }
        return res;
    }
}

​ 也可以用dfs解决。

5.二叉树的深度

剑指 Offer 55 - I. 二叉树的深度

​ 递归寻找 每次向下搜索不为空+1,由于有两个方向所以每次返回时取最大路径。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {

        if(root == null){
            return 0;
        }
        return Math.max(maxDepth(root.left),maxDepth(root.right))+1;

    }
    
}

6.num最大子序列

437. 路径总和 III

​ 之前做过数组类型的求和的最大子序列和乘积的最大子序列。

​ 但这道题在二叉树中寻找累加等于target的路径数

/**
 * 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 pathSum(TreeNode root, int targetSum) {
        //边界条件
        if(root==null){
            return 0;
        }
        int res = dfs(root,targetSum);
        res+=pathSum(root.left,targetSum);
        res+=pathSum(root.right,targetSum);

        return res;
        
    }

    public int dfs(TreeNode root,int targetSum){
        int res =0;
        if(root==null){
            return 0;
        }
        int val = root.val;
        if(val == targetSum){
            res++;
        }
        res+=dfs(root.left,targetSum-val);
        res+=dfs(root.right,targetSum-val);
        return res;
    }
}

7. 是否为子结构

剑指 Offer 26. 树的子结构

​ 判断一棵树是不是另外一棵树的子结构,空树不是任何一棵树的子结构。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /**
    使用递归来判断是不是子节点
    这里使用了两个递归
    B是A的子结构
     */
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        //前置条件
        if(A==null||B == null){
            return false;
        }

        //第一个递归寻找当前节点下是否存在相同的子树
        if(isEqualTree(A,B)){
            return true;
        }

        // 左子树右子树两个方向进行递归
        return isSubStructure(A.left,B)||isSubStructure(A.right,B);
    }

    public boolean isEqualTree(TreeNode a, TreeNode b){
        // 如果b树被遍历完,就可以判定为真
        if(b==null) return true;
        // 如果a树被遍历完,还没有找到b树,就可以判定为假
        if(a == null||a.val!=b.val) return false;


        return isEqualTree(a.left,b.left) && isEqualTree(a.right,b.right);


    }
}

8.改造为双向链表

剑指 Offer 36. 二叉搜索树与双向链表

		 4
	   /   \ 
	 2       5
   /   \
 1       3     

转换成双向链表的顺序是 1-2-3-4-5

/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution {
    // 临时变量 用于存储值
    Node pre,head;
    public Node treeToDoublyList(Node root) {
        // 边界
        if(root == null) return null;
        // 用有个dfs来连接链表
        dfs(root);

        // 最后进行首尾连接
        head.left = pre;
        pre.right = head;
        

        return head;

    }
    public void dfs(Node cur){
        //结束条件
        if(cur == null) return;
        //中序遍历  head的作用只用于储存第一个节点,
        dfs(cur.left);
        if(pre==null) {
            head =cur;
        }else if(pre != null){
            pre.right =cur;// pre储存上一个节点,二叉树不是双向的
        }
        // 连接 双向链表
        cur.left = pre;

        pre = cur;

        dfs(cur.right);

    }
}

9.找和为target路径

剑指 Offer 34. 二叉树中和为某一值的路径

注意要求是从根节点到叶子节点 路径总和等于给定目标和的路径。

只需要考虑遍历所以分支就可以了

/**
 * 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 {
    /**
        进行递归
     */
    List<List<Integer>> res;
    int target;
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        res = new LinkedList<>();
        this.target = target;
        LinkedList<Integer> list = new LinkedList<>();

        dfs(root,0,list);


        return res;
    }

    public void dfs(TreeNode root,int sum,LinkedList<Integer> list){
        if(root == null){
            return;
        }

        //  从根节点到叶子节点 路径总和等于给定目标和的路径。
        if(root.left==null&&root.right == null){
            if(sum+root.val == target){
                list.add(root.val);
                res.add(new LinkedList<Integer>(list));
                list.removeLast();
            }

            return;
        }
        

        // 回溯
        list.add(root.val);
        dfs(root.left,sum+root.val,list);
        dfs(root.right,sum+root.val,list);

        list.removeLast();

    }
}

10.搜索两节点的公共节点(二叉搜索树)

剑指 Offer 68 - I. 二叉搜索树的最近公共祖先

​ 注意是二叉搜索树。回溯的思想可以粗略的理解为利用return 调用方法去探索不同分支。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // 边界条件
        if(root == null){
            return null;
        }
        // 利用二叉搜索树的性质
        // 父节点值大小在两个值的中间部分
        if(root.val>p.val&&root.val>q.val){
            return lowestCommonAncestor(root.left,p,q);
        }

        if(root.val<p.val&&root.val<q.val){
            return lowestCommonAncestor(root.right,p,q);
        }
        return root;       
    }

}

11.搜索两节点的公共节点(二叉树)

剑指 Offer 68 - II. 二叉树的最近公共祖先

​ 这个是二叉树,需要完全遍历。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /***
    1.一个左子树,一个右子树,
    2.两个都在左
    3.都在右
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root== null) return null;

        if(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;
        }

        if(left==null){
            return right;
        }

        if(right == null){
            return left;
        }

        return null;

    }

    
}

12. 广度优先搜索

剑指 Offer 32 - III. 从上到下打印二叉树 III

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        // 边界条件
        if(root==null) return res;
        Queue<TreeNode> d = new LinkedList<>(); 

        d.add(root);
        int counter =1;
       
        while(!d.isEmpty()){
            int num=d.size();
            List<Integer> list = new ArrayList<>();
            for(int i = 0;i<num;i++){
                TreeNode node = d.poll();
                list.add(node.val);
                if(node.left!=null) d.add(node.left);
                if(node.right!=null) d.add(node.right);
                
            }
            res.add(list);

        }
        for(int i =1;i<res.size();i+=2){
            Collections.reverse(res.get(i));
        }

        return res;
    }
}

二、二叉搜索树

​ 又叫二叉排序树,二叉查找树,如果左子树不为空,左子树的值小于根节点的值。如果右子树不为空,右子树的值大于根节点的值。

剑指 Offer 54. 二叉搜索树的第k大节点

可能出现的情况的是

       5
      / \
     3   6
    / \
   2   4
  /
 1
 	k = 3;  res = 4  root节点先遍历右子树。   每遍历一个k--;如果向右没有找到那么就返回去遍历上个节点的左子树,左子树存在如果 k 不为1 那么就去遍历右子树。
 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /**
        右子树节点为 大于的值
     */
    int res,k;
    public int kthLargest(TreeNode root, int k) {
        this.res = 0;
        this.k = k;

        dfs(root);

        return res;

    }

    public void dfs(TreeNode root){
        if(root==null)return;
        dfs(root.right);
        if(k==0)return;

        if(--k == 0){
            res = root.val;
            return;
        }
        
        dfs(root.left);


    }
}

230. 二叉搜索树中第K小的元素

​ 中序遍历

/**
 * 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 {
    /**
    二叉搜索树 做左子树 < 根节点 < 右子树
    中序遍历左子树 - 根节点 -右子树的顺序进行的
    二叉搜素树的中序遍历是按照增加的顺序进行的。
    使用中序遍历 找到第k小的元素
     */
    public int kthSmallest(TreeNode root, int k) {
        Deque<TreeNode> stack = new ArrayDeque<TreeNode>();

        // 中序遍历

        while(root != null || !stack.isEmpty()){
            while(root!= null){
                // 把所有的根节点+左子树压入栈中
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            k--;
            if(k==0){
                break;
            }
            root =root.right;
        }
        return root.val;
    }
}

剑指 Offer 33. 二叉搜索树的后序遍历序列

class Solution {
    /**
    后序遍历:左子树  右子树  根节点 ;
    根据这个特点 根节点一定在最后


     */
    public boolean verifyPostorder(int[] postorder) {

        Deque<Integer> stack = new LinkedList<>();
        int pre = Integer.MAX_VALUE;

        // 最后的一定是根节点
        for(int i= postorder.length-1;i>=0;i--){
            // 左子树元素小于栈中的元素
            if(postorder[i]>pre){
                return false;
            }
            while(!stack.isEmpty()&&postorder[i]<stack.peek()){
                pre = stack.pop();
            }

            stack.push(postorder[i]);
        }

        


        return true;
    }
}

三、二叉平衡树

​ 他是一棵空树或它的左右两个子树的高度差绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。平衡二叉树较好的解决了二叉查找树退化成链表的问题。相对于二叉查找树稳定了许多。

​ 平衡二叉树和二叉查找树大部分操作类似,但是平衡二叉树在插入删除时平衡可能会改变。

剑指 Offer 55 - II. 平衡二叉树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    /**
        平衡二叉树:
     */
    boolean res=true;
    public boolean isBalanced(TreeNode root) {

        // 边界条件
        if(root==null) return true;
        count_height(root);
        
        return res;
    } 

    public int count_height(TreeNode root){
        if(root == null){
            return 0;
        }

        int left = count_height(root.left);
        int right = count_height(root.right);

        if(Math.abs(left-right)>1){
            res = false;
        }

        return Math.max(left,right)+1;

    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值