美文网首页
[leetcode]binary-tree-preorder-t

[leetcode]binary-tree-preorder-t

作者: 这是朕的江山 | 来源:发表于2016-08-30 20:53 被阅读31次

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].
二叉树的前序遍历
解法一:递归

import java.util.ArrayList;
/**
 * 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) {
        ArrayList<Integer>a=new ArrayList<Integer>();
        if (root==null)
            return a;
        a.add(root.val);
        a.addAll(preorderTraversal(root.left));
        a.addAll(preorderTraversal(root.right));
        return a;
    }
}

解法二:迭代

import java.util.*;

/**
 * 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) {
               ArrayList<Integer>a=new ArrayList<Integer>();
        if (root==null)
            return a;
        Stack<TreeNode>stack1=new Stack<TreeNode>();
        Queue<TreeNode>queue=new LinkedList<TreeNode>();
        stack1.push(root);
        while (!stack1.empty())
        {
            TreeNode t=stack1.pop();
            if (t.right!=null)
                stack1.push(t.right);
            if (t.left!=null)
                stack1.push(t.left);
            queue.offer(t);
        }
        while (!queue.isEmpty())
        {
            a.add(queue.poll().val);
        }
        return a;
    }
}

相关文章

网友评论

      本文标题:[leetcode]binary-tree-preorder-t

      本文链接:https://www.haomeiwen.com/subject/ilcqettx.html