二叉树水平顺序遍历level-order traversal

有个很有名的算法叫广度优先搜索(Breadth-First Search)BFS,这个算法被用于遍历或者搜索数据结构,比如树或者图。

BFS使用到树上就是level-order traversal.

进行广度优先搜索算法时,需要用到java的Queue,Queue是继承自Collection的,所以Collection中的方法都是可以用的。

Queue常用方法:offer、poll、size、isEmpty等

LeetCode中level-order traversal的例子:

/**
 * 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>> ans = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        if (root != null) {
            q.offer(root);
        }
        TreeNode cur;
        while (!q.isEmpty()) {
            int size = q.size();
            List<Integer> subAns = new LinkedList<Integer>();
            for (int i = 0; i < size; ++i) {        // traverse nodes in the same level
                cur = q.poll();
                subAns.add(cur.val);                // visit the root
                if (cur.left != null) {
                    q.offer(cur.left);              // push left child to queue if it is not null
                }
                if (cur.right != null) {
                    q.offer(cur.right);             // push right child to queue if it is not null
                }
            }
            ans.add(subAns);
        }
        return ans;
    }
}

Since each node in the tree will be pushed into the queue exactly once, the time complexity for level-order traversal is O(N), where N is the total number of nodes in the tree.

What about the space complexity? We have to maintain a queue to help us to do the traversal. And the size of the queue will be at most N because each node will be pushed into the queue exactly once. Therefore, the space complexity of level-order traversal is also O(N).

 

 

还有另一个算法是深度优先搜索(Depth-First Search)DFS,这个可以有两种实现方案,可以用递归实现也可以用迭代实现。

比较简单,可以看下面的参考

总体说,深度操作(深度优先遍历、先序、中序和后序)既可以用递归实现也可以用迭代实现,迭代实现需要用到栈。广度操作好像只能用迭代实现,需要用到队列。

 

参考:

树的广度优先遍历和深度优先遍历(递归非递归、Java实现)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值