★[leetCode] 二叉树专题

二叉树的层序遍历

使用一个队列来访问即可,注意每一层的元素个数可以在一开始访问该层的时候,用队列里面的元素个数来表示出来

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res =new ArrayList<>();
        Queue<TreeNode> queue=new LinkedList<>();
        if (root!=null) queue.add(root);
        while (!queue.isEmpty()){
            int size=queue.size();
            List<Integer> tem=new ArrayList<>();
            for (int i=0;i<size;i++){
                TreeNode t=queue.poll();
                tem.add(t.val);
                if (t.left!=null) queue.add(t.left);
                if (t.right!=null) queue.add(t.right);
            }
            res.add(tem);
        }
        return  res;
    }
}
二叉树的统一递归法

写递归的步骤:

  1. 先确定递归函数要用到的参数已经返回类型
  2. 确定递归终止条件
  3. 确定每一次递归函数里的处理逻辑
//以前序遍历为例,其他两个改一下顺序就好了
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        preorder(root, result);
        return result;
    }

    public void preorder(TreeNode root, List<Integer> result) {
        if (root == null) {
            return;
        }
        result.add(root.val);
        preorder(root.left, result);
        preorder(root.right, result);
    }
}
二叉树的统一迭代遍历

这里采用的是标记法,依旧是用栈这种数据结构。
访问一个元素,依次再向栈里压入它的字节点和它本身这个节点(按照想要的访问顺序)。

由于它本身这个节点是已经被访问过了,所以做一个标记,在它后面插入一个null节点,这样就知道哪些是已经访问过的,哪些是还没有访问过的节点。

访问过的节点就直接加入数组输出。

class Solution {
     public List<Integer> inorderTraversal(TreeNode root) {
       List<Integer> res=new ArrayList<>();
        Deque<TreeNode> stack=new LinkedList<>();
        if(root!=null) stack.push(root);
        while (!stack.isEmpty()){
            TreeNode top=stack.pollLast();
            if (top!=null){
                if (top.right!=null) stack.addLast(top.right);
                stack.addLast(top);
                stack.addLast(null);
                if (top.left!=null) stack.addLast(top.left);
            }else {
                TreeNode st=stack.pollLast();
                res.add(st.val);
            }
        }
        return res;
}}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值