博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[lintcode easy]Binary Tree Preorder Traversal
阅读量:5101 次
发布时间:2019-06-13

本文共 2635 字,大约阅读时间需要 8 分钟。

Binary Tree Preorder Traversal

 

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

 
Given:
1   / \  2   3 / \4   5

return [1,2,4,5,3].

Challenge

Can you do it without recursion?

 

前序遍历两种方式,递归与非递归方式。

首先要明确前序遍历,顺序是先父节点,然后左子节点,右子节点。

 

The key to solve this problem is to understand the following:

  1. What is preorder? (parent node is processed before its children)

使用递归的方法:

/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {    /**     * @param root: The root of binary tree.     * @return: Preorder in ArrayList which contains node values.     */    ArrayList
list=new ArrayList
(); public ArrayList
preorderTraversal(TreeNode root) { // write your code here if(root!=null) { helper(root); } return list; } public void helper(TreeNode p) { list.add(p.val); if(p.left!=null) { helper(p.left); } if(p.right!=null) { helper(p.right); } }}

 

非递归:

  1. Use Stack from Java Core library
  2. It is not obvious what preorder for some strange cases. However, if you draw a stack and manually execute the program, how each element is pushed and popped is obvious.

The key to solve this problem is using a stack to store left and right children, and push right child first so that it is processed after the left child.

 

public class TreeNode {    int val;    TreeNode left;    TreeNode right;    TreeNode(int x) { val = x; }} public class Solution {    public ArrayList
preorderTraversal(TreeNode root) { ArrayList
list = new ArrayList
(); if(root == null) return list; Stack
stack = new Stack
(); stack.push(root); while(!stack.empty()){ TreeNode cur= stack.pop(); list.add(cur.val); if(cur.right != null){ stack.push(cur.right); } if(n.left != null){ stack.push(cur.left); } } return list; }}

Keep in mind that stack is a FILO data type, so when we process the data, we need to push the right children first, and then left children.

 

转载于:https://www.cnblogs.com/kittyamin/p/4970590.html

你可能感兴趣的文章
linux基础命令-chgrp/chown/chomd
查看>>
待整理
查看>>
iOS 6
查看>>
Nginx入门篇-基础知识与linux下安装操作
查看>>
一次动态sql查询订单数据的设计
查看>>
C# 类(10) 抽象类.
查看>>
1.linux ping:unknown host www.***.***
查看>>
无向图求桥 UVA 796
查看>>
Nginx+Keepalived 实现双击热备及负载均衡
查看>>
五分钟搭建WordPress博客(二)
查看>>
Vue_(组件通讯)子组件向父组件传值
查看>>
jvm参数
查看>>
Something-Summary
查看>>
Spring学习笔记
查看>>
6个有用的MySQL语句
查看>>
linux c/c++ IP字符串转换成可比较大小的数字
查看>>
我对前端MVC的理解
查看>>
[网络流24题] 最长k可重区间集问题 (费用流)
查看>>
剑指offer系列32-----对称二叉树的判断
查看>>
Silverlight实用窍门系列:19.Silverlight调用webservice上传多个文件【附带源码实例】...
查看>>