Binary Tree Preorder Traversal Java版本

原创 2015年07月06日 16:57:45
二叉树先序遍历
思路:

     不使用递归前序遍历,可以借助栈的帮助实现。对于一个特定节点,前序遍历顺序为: 根,左,右。所以入栈顺序为 右,左,根。由于根节点的遍历和展开(研究其右节点和左  节点)是同时的,所以根节点出栈的同时即可加入遍历结果中,然后研究其右节点和左节点,如果不为空即可入栈。

/**
 * Definition for a binary tree node.
 * 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> returnList = new ArrayList<Integer>();
 
        if(root == null)
            return returnList;
 
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
 
        while(!stack.empty()){
            TreeNode n = stack.pop();
            returnList.add(n.val);
 
            if(n.right != null){
                stack.push(n.right);
            }
            if(n.left != null){
                stack.push(n.left);
            }
 
        }
        return returnList;
    }
}


[leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal@Java解题报告

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/...

LeetCode 144 — Binary Tree Preorder Traversal(C++ Java Python)

题目:http://oj.leetcode.com/problems/binary-tree-preorder-traversal/ Given a binary tree, return the p...

Construct Binary Tree from Preorder and Inorder Traversal (Java)

Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume ...

Binary Tree Preorder Traversal (Java)

Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary ...

【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal(构造二叉树)】

【106-Construct Binary Tree from Preorder and Inorder Traversal(通过前序和中序遍历构造二叉树)】【LeetCode-面试算法经典-Java...

leetcode No105. Construct Binary Tree from Preorder and Inorder Traversal

Question: Given preorder and inorder traversal of a tree, construct the binary tree. 根据树的前序遍历和中序遍历...

144.Binary Tree Preorder Traversal

题目链接:binary-tree-preorder-traversal import java.util.ArrayList; import java.util.List; import java.u...
  • ever223
  • ever223
  • 2015年03月19日 00:34
  • 340

【leetcode】Construct Binary Tree from Preorder and Inorder Traversal

问题: 给定二叉树的前序和中序遍历,重构这课二叉树. 分析: 前序、中序、后序都是针对于根结点而言,所以又叫作先根、中根、后根(当然不是高跟)。 前序:根  左 右 中序:左  根 右 对二叉树,我们...

LeetCode 之 Binary Tree Preorder Traversal(树)

【算法核心思想】 1)初始化Vector,树空直接返回,不为空进入压栈弹栈机制; 2)(按从根出发先遍历左子树再遍历右子树的遍历思想),依次循环从根出发,先右子树先入栈左子树后入栈(子树弹栈是和压栈顺...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Binary Tree Preorder Traversal Java版本
举报原因:
原因补充:

(最多只允许输入30个字)