当前位置:网站首页>Force buckle 144 Preorder traversal of binary tree

Force buckle 144 Preorder traversal of binary tree

2022-07-07 07:59:00 Yangshiwei....

subject :

 

analysis :

Preorder traversal is to first self node , Then the left node , Last right node , We can write a recursive function to realize .

Code :

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list =new ArrayList();
        first(root,list);
        return list;
    }
    public void first(TreeNode node,List<Integer> list){
        if(node!=null){
            list.add(node.val);
            if(node.left!=null){
                first(node.left,list);
            }if(node.right!=null){
                first(node.right,list);
            }
        }
    }
}

原网站

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