[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<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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值