LeetCode brushing notes _102. Binary tree traversal

The topic is from LeetCode

[102. Level traversal of binary tree](https://leetcode-cn.com/problems/binary-tree-level-order-traversal

Other solutions or source code can be accessed: tongji4m3

description

Give you a binary tree, please return the node value obtained by traversing it in order. (That is, visit all nodes layer by layer, from left to right).


示例:
二叉树:[3,9,20,null,null,15,7],

   3
  / \
 9  20
   /  \
  15   7
返回其层次遍历结果:

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

Ideas

The idea of ​​recursion: recursively start from the root node and the height is 0. When entering a certain floor for the first time, open up a new space, and then enter the same floor and join directly according to his height

Code

private List<List<Integer>> result = new LinkedList<>();

public List<List<Integer>> levelOrder(TreeNode root)
{
    
    
    recursive(root, 0);
    return result;
}

private void recursive(TreeNode node, int height)
{
    
    
    if(node==null)
    {
    
    
        return;
    }
    //最多就是等于,不会大于,因为每层不满足都会构建
    if(height==result.size())
    {
    
    
        result.add(new LinkedList<>());
    }
    result.get(height).add(node.val);

    recursive(node.left,height+1);
    recursive(node.right,height+1);
}

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108507570