1. 程式人生 > >leetcode(NOWCODER)---binary-tree-preorder-traversal

leetcode(NOWCODER)---binary-tree-preorder-traversal

時間限制:1秒 空間限制:32768K 熱度指數:23954
本題知識點: 樹 leetcode
演算法知識視訊講解
題目描述

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].

Note: Recursive solution is trivial, could you do it iteratively?

思路:https://blog.csdn.net/ccnuacmhdu/article/details/85227092

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    private ArrayList<Integer> list = new ArrayList<Integer>();
    public ArrayList<
Integer>
preorderTraversal(TreeNode root) { //這道題明顯類似於上一題後序遍歷的解法,後序遍歷用棧: //https://blog.csdn.net/ccnuacmhdu/article/details/85227092 //這道題依然是用棧!!細想下,不能用佇列!!遞迴與棧本一家啊,兩道非遞迴遍歷題感觸深 if(root == null){ return list; } ArrayDeque<TreeNode> stack = new ArrayDeque
<TreeNode>(); stack.addFirst(root); while(stack.isEmpty() == false){ TreeNode node = stack.removeFirst(); list.add(node.val); if(node.right != null){ stack.addFirst(node.right); } if(node.left != null){ stack.addFirst(node.left); } } return list; } }