[leetcode]binary-tree-preorder-traversal

1750 단어
Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tree{1,#,2,3}, 1\2/3 return[1,2,3]. 두 갈래 나무의 앞 순서 역행 해법 1: 역귀
import java.util.ArrayList;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList preorderTraversal(TreeNode root) {
        ArrayLista=new ArrayList();
        if (root==null)
            return a;
        a.add(root.val);
        a.addAll(preorderTraversal(root.left));
        a.addAll(preorderTraversal(root.right));
        return a;
    }
}

해법2:교체
import java.util.*;

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList preorderTraversal(TreeNode root) {
               ArrayLista=new ArrayList();
        if (root==null)
            return a;
        Stackstack1=new Stack();
        Queuequeue=new LinkedList();
        stack1.push(root);
        while (!stack1.empty())
        {
            TreeNode t=stack1.pop();
            if (t.right!=null)
                stack1.push(t.right);
            if (t.left!=null)
                stack1.push(t.left);
            queue.offer(t);
        }
        while (!queue.isEmpty())
        {
            a.add(queue.poll().val);
        }
        return a;
    }
}

좋은 웹페이지 즐겨찾기