[leet code] Binary Tree Preorder Traversal

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 preorderTraversal(TreeNode root) {
        
        // define linklist
        ArrayList nodeVal = new ArrayList();
        
        // root == null
        if(root == null) return nodeVal;
        
        //recursive call
        pre(nodeVal, root);
        
        // return link list
        return nodeVal;
    }
    //recursive function
    public void pre(ArrayList 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 preorderTraversal(TreeNode root) {
        // define linklist and stack
        ArrayList nodeVal = new ArrayList();
        Stack 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;
    }
}

 

你可能感兴趣的:(interview,preparation,algorithm,binary,tree,array,list,stack,java)