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?
Subscribe to see which companies asked this question.
題目
給出一棵二叉樹,傳回其節點值的前序周遊。
分析
前序排序的非遞歸算法是相對簡單的,隻要使用棧,保證right,left的順序
代碼
方法一,非遞歸,運用一個棧即可
/**
* 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.
*/
public ArrayList<Integer> preorderTraversal(TreeNode root) {
// write your code here
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<Integer> preorder = new ArrayList<Integer>();
if (root == null) {
return preorder;
}
stack.push(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
preorder.add(node.val);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return preorder;
}
}
複制
方法二: 遞歸周遊
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Traversal(root,res);
return res;
}
private void Traversal(TreeNode root, List<Integer> res) {
if(root == null)
return;
res.add(root.val);
Traversal(root.left,res);
Traversal(root.right,res);
}
複制
Paste_Image.png
方法三 : 分治法
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(root == null)
return res;
res.add(root.val);
List<Integer> left = preorderTraversal(root.left);
List<Integer> right = preorderTraversal(root.right);
res.addAll(left);
res.addAll(right);
return res;
}
複制
Paste_Image.png