leetcode--Binary Tree Level Order Traversal

本文介绍了一种解决二叉树层次遍历问题的方法。通过两种不同的实现方式,详细展示了如何从根节点开始,按层级顺序收集每个节点的值。

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


题意:给定二叉树。返回每层的节点值,从左到右。

分类:二叉树


解法1:层次遍历。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		if(root == null) return res;
		List<Integer> t = new ArrayList<Integer>();
		int low = 0;
		int high = 0;
		int ceng = 0;
		stack.add(root);
		t.add(root.val);
		res.add(t);
		t = new ArrayList<Integer>();;
		while(low<=high){			
			TreeNode cur = stack.get(low);			
			if(cur.left!=null){
				stack.add(cur.left);
				t.add(cur.left.val);
				high++;
			}
			if(cur.right!=null){
				stack.add(cur.right);
				t.add(cur.right.val);
				high++;
			}
			if(low==ceng){
				if(t.size()!=0) res.add(t);
				t = new ArrayList<Integer>();
				ceng = high;
			}
			low++;
		}
		return res;
    }
}


解法2:思路和解法1一样,只是代码更加简洁。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        LinkedList<Integer> curqueue = new LinkedList<Integer>();
        if(root==null) return res;
        int level = 1;
        queue.add(root);
        while(queue.size()>0){
            TreeNode cur = queue.poll();
            curqueue.add(cur.val);
            if(cur.left!=null){
                queue.add(cur.left);
            }
            if(cur.right!=null){
                queue.add(cur.right);
            }
            if(--level==0){
                ArrayList<Integer> arr = new ArrayList<Integer>(curqueue);
                res.add(arr);
                level = queue.size();
                curqueue.clear();
            }
        }
        return res;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值