1. 程式人生 > >[Leetcode 144]二叉樹前序遍歷Binary Tree Preorder Traversal

[Leetcode 144]二叉樹前序遍歷Binary Tree Preorder Traversal

public list left 前序 output nod roo strong while

【題目】

Given a binary tree, return the preordertraversal of its nodes‘ values.

Example:

Input: [1,null,2,3]
   1
         2
    /
   3

Output: [1,2,3]

【思路】

有參考,好機智,使用堆棧壓入右子樹,暫時存儲。

左子樹遍歷完成後遍歷右子樹。

【代碼】

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 
*/ class Solution { public List<Integer> preorderTraversal(TreeNode root) { LinkedList<Integer> ans=new LinkedList<Integer>(); Stack<TreeNode> tmp=new Stack<TreeNode>(); while(root!=null){ ans.add(root.val); if(root.right!=null
){ tmp.push(root.right); } root=root.left; if(root==null&&!tmp.isEmpty()){ root=
tmp.pop(); } } return ans; } }

[Leetcode 144]二叉樹前序遍歷Binary Tree Preorder Traversal