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?
Binary tree第一反应仍然是递归, 不幸的是该题注释问能不能不用递归, 于是就杯具了 (基础不好没办法).仍然先用递归实现 (非常直接):
递归体内先存当前节点, 如果该节点有左子节点, 以左子节点作为参数递归调用递归体; 如果该节点有右子节点, 以右节点作为参数递归调用递归体.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
// define linklist
ArrayList<Integer> nodeVal = new ArrayList<Integer>();
// root == null
if(root == null) return nodeVal;
//recursive call
pre(nodeVal, root);
// return link list
return nodeVal;
}
//recursive function
public void pre(ArrayList<Integer> nodeVal, TreeNode node){
// add root
nodeVal.add(node.val);
// if left != null recursive call
if(node.left != null) pre(nodeVal, node.left);
// if right != null recursive call
if(node.right != null) pre(nodeVal, node.right);
}
}
对于不使用递归, 最大问题是程序如何记录节点的顺序. 由于现在还处于做题初级阶段, 没遇过的状况是无论如何都没思路的, 只能上网找.. 结果是可以利用stack先进后出的特性实现记录节点的顺序.
也就是说, 每次都先将右子节点入栈, 于是每次出栈的顺序为:
1. 当前节点
2. 左子节点(如果有)
3. 右子节点(如果有)
4. 同层右节点
......
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
// define linklist and stack
ArrayList<Integer> nodeVal = new ArrayList<Integer>();
Stack<TreeNode> st = new Stack();
// root == null
if(root == null) return nodeVal;
// for root node
st.push(root);
// use stack to implement the order of node
while (!st.isEmpty()){
TreeNode cur = st.peek();
nodeVal.add(cur.val);
st.pop();
if (cur.right != null) st.push(cur.right);
if (cur.left != null) st.push(cur.left);
}
return nodeVal;
}
}