题目:二叉树的前序遍历

来源:互联网 发布:房租占收入比例 知乎 编辑:程序博客网 时间:2024/04/24 14:35

/**
* 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: The root of binary tree.
     * @return: Preorder in ArrayList which contains node values.
     */
    ArrayList<Integer> result = new ArrayList<>();
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        if(root==null) return result;
         result.add(root.val);
         if(root.left!=null){
              preorderTraversal(root.left);
         }
         if(root.right!=null){
              preorderTraversal(root.right);
         }
         return result;
    }
}
0 0
原创粉丝点击