Binary Tree Preorder Traversal
今天是一道有關(guān)基礎(chǔ)的題目,來(lái)自LeetCode,難度為Medium,Acceptance為37.8%。
題目如下
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?
解題思路及代碼見(jiàn)閱讀原文
回復(fù)0000查看更多題目
解題思路
二叉樹的前序,中序,后續(xù)遍歷都是數(shù)據(jù)結(jié)構(gòu)課程的基礎(chǔ)了。
不做過(guò)多解釋了,大家權(quán)當(dāng)回憶一下大學(xué)時(shí)代吧。
代碼如下
Java版
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
if(null != root)
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
list.add(node.val);
if(node.right != null)
stack.push(node.right);
if(node.left != null)
stack.push(node.left);
}
return list;
}
}
關(guān)注我
該公眾號(hào)會(huì)每天推送常見(jiàn)面試題,包括解題思路是代碼,希望對(duì)找工作的同學(xué)有所幫助
image