LintCode66. Binary tree preorder traversal

description

It is given a binary tree, whose nodes preorder traversal return value.

The first data as the root node, followed by its left and right son son node value, "#" indicates that the child node does not exist.
The number of nodes does not exceed 20
Have you encountered this problem in a real interview?
Sample
Sample 1:

Input: {1,2,3}
Output: [1,2,3]
Explanation:
1
/
23
it will be {1,2,3} into a sequence
preorder traversal
Sample 2:

Input: {1, # 2, 3}
Output: [1,2,3]
Explanation:
1

2
/
3
will be serialized as {1, # 2, 3}
preorder traversal

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: A Tree
     * @return: Preorder in ArrayList which contains node values.
     */
       public List<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        List<Integer> listData = new ArrayList<>();
        if(root == null){
            return listData;
        }
        listData.add(root.val);
        treeList(root.left,listData);
        treeList(root.right,listData);
        return listData;
    }

    public void treeList(TreeNode root, List<Integer> listData) {
        if (root!=null) {
                 listData.add(root.val);
                treeList(root.left, listData);
                treeList(root.right, listData);
            
        }
    }
}

Guess you like

Origin blog.csdn.net/leohu_v5/article/details/91817772