设为首页 加入收藏

TOP

Leetcode:Binary Tree Preorder Traversal
2015-07-20 17:18:49 来源: 作者: 【 】 浏览:2
Tags:Leetcode 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?

题目要求用迭代的方法,而不是递归。首先介绍下迭代和递归的区别:

递归:所谓递归,简而言之就是应用程序自身调用自身,以实现层次数据结构的查询和访问。

迭代:迭代是重复反馈过程的活动,其目的通常是为了逼近所需目标或结果。每一次对过程的重复称为一次”迭代”,而每一次迭代得到的结果会作为下一次迭代的初始值。

迭代与递归的区别:

//以下以一个斐波那契数列的例子说明:

//----------------------------------
//1.迭代方法:
public class Fab_iterate 
{
    public static void main(String[] args) 
  {
   System.out.println("结果是:"+Fab(8));   //求第八个位置的数
  }
  public static long Fab(int index)   //斐波那契数列
  {
        if(index == 1 || index == 2)
       {
            return 1;
       }
      else
      {
           long f1 = 1L;
           long f2 = 1L;
           long f3 = 0;
           for(int i = 0;i < index-2;i ++)  //迭代求值
           {      
            f3 = f1 + f2;
               f1 = f2;
               f2 = f3;
            }
           return f3;
       }
   }
}

//2.递归方法:

public class Fab_recursion 
{
   public static void main(String[] args)
  {
   System.out.println("结果是:"+fab(8));    //求第八个位置的数
  }
   public static long fab(int index)    //斐波那契数列
  {
      if(index == 1 || index == 2)
     {
       return 1;
      }
     else
     {
       return fab(index-1)+fab(index-2);    //递归求值
     }
    }
}

解题思路:首先当根节点不为空时,把根节点压入栈中,然后进行迭代:当栈不为空时,把栈顶元素出栈,并把该元素对应的数值保存到数值中。判断该节点的右节点和左节点是否为空,如果不为空,则依次压入栈中。若栈不为空,继续进行迭代。

实现代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector
  
    preorderTraversal(TreeNode *root) {
        if (root==NULL) {
            return vector
   
    (); } vector
    
      result; stack
     
       treeStack; treeStack.push(root); while (!treeStack.empty()) { TreeNode *temp = treeStack.top(); result.push_back(temp->val); treeStack.pop(); if (temp->right!=NULL) { treeStack.push(temp->right); } if (temp->left!=NULL) { treeStack.push(temp->left); } } return result; } };
     
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇(hdu step 3.2.5)Humble Numbers(.. 下一篇poj2632Crashing Robots

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·MySQL 基础入门视频 (2025-12-26 23:20:22)
·小白入门:MySQL超详 (2025-12-26 23:20:19)
·关于 MySQL 数据库学 (2025-12-26 23:20:16)
·SOLVED: Ubuntu 24.0 (2025-12-26 22:51:53)
·Linux 常用命令最全 (2025-12-26 22:51:50)