LintCode66. 二叉树的前序遍历

描述

给出一棵二叉树,返回其节点值的前序遍历。

首个数据为根节点,后面接着是其左儿子和右儿子节点值,"#"表示不存在该子节点。
节点数量不超过20
您在真实的面试中是否遇到过这个题?
样例
样例 1:

输入:{1,2,3}
输出:[1,2,3]
解释:
1
/
2 3
它将被序列化为{1,2,3}
前序遍历
样例 2:

输入:{1,#,2,3}
输出:[1,2,3]
解释:
1

2
/
3
它将被序列化为{1,#,2,3}
前序遍历

/**
 * 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);
            
        }
    }
}

猜你喜欢

转载自blog.csdn.net/leohu_v5/article/details/91817772