当前位置:网站首页>[※ leetcode refers to offer 32 - II. Print binary tree II from top to bottom (simple)]

[※ leetcode refers to offer 32 - II. Print binary tree II from top to bottom (simple)]

2022-04-23 21:02:00 Minaldo7

subject :

Print binary tree from top to bottom , Nodes of the same layer are printed from left to right , Print each layer to a line .

for example :
Given binary tree : [3,9,20,null,null,15,7],
 Insert picture description here
Return its hierarchical traversal result :
 Insert picture description here
Tips :

Total number of nodes <= 1000

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

The problem solving process :

java Recursive hierarchical traversal
from LeetCode user : Movable dummy

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
class Solution {
    
    List<List<Integer>> node = new ArrayList();
    public List<List<Integer>> levelOrder(TreeNode root) {
    
        bianli(root,0);
        return node;
    }

    public void bianli(TreeNode root, int k){
    
        if(root != null){
    
            if(node.size()<=k) node.add(new ArrayList());
            node.get(k).add(root.val);
            bianli(root.left, k+1);
            bianli(root.right, k+1);
        } 
    }
}

Execution results :

 Insert picture description here

版权声明
本文为[Minaldo7]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/111/202204210544479775.html