LeetCode-Binary Tree Postorder Traversal,binarysearchtree

來源:互聯網
上載者:User

LeetCode-Binary Tree Postorder Traversal,binarysearchtree

題目:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/

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

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

源碼:Java版本
演算法分析:雙棧。時間複雜度O(n),空間複雜度O(n)

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> postorderTraversal(TreeNode root) {        List<Integer> result=new ArrayList<Integer>();          Stack<TreeNode> stack=new Stack<TreeNode>();         Stack<Integer> cntStack=new Stack<Integer>();        TreeNode node=root;          int label;        do {            while(node!=null) {                stack.push(node);                cntStack.push(0);                node=node.left;            }            if(!stack.isEmpty()) {                node=stack.pop();                label=cntStack.pop();                if(label==0) {                    cntStack.push(1);                    stack.push(node);                    node=node.right;                }else {                    result.add(node.val);                    node=null;  //import                }            }                    }while(!stack.isEmpty());                return result;    }}
代碼解釋:cntStack用來標誌頂點是第一次還是第二次出棧。第一次出棧需要訪問其由節點,第二次出棧直接存取它。


valentain tree 由來

Little Valentine liked playing with binary trees very much. Her favorite game was constructing randomly looking binary trees with capital letters in the nodes.

This is an example of one of her creations:
D
/ \
/ \
B E
/ \ \
/ \ \
A C G
/
/
F

To record her trees for future generations, she wrote down two strings for each tree: a preorder traversal (root, left subtree, right subtree) and an inorder traversal (left subtree, root, right subtree). For the tree drawn above the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG.

She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried it).

Now, years later, looking again at the strings, she realized that reconstructing the trees was indeed possible, but only because she never had used the same letter twice in the same tree.

However, doing the reconstruction by hand, soon turned out to be tedious.

So now she asks you to write a program that does the job for her!

Input

The input will contain one or more test cases.

Each test case consists of one line containing two strings preord and inord, representing the preorder traversal and inorder traversal of a binary tree. Both strings consist of unique capital letters. (Thus they are not longer than 26 characters.)

Input is terminated by end of fil......餘下全文>>
 
UVa 548 - Tree 我怎錯了?

AC 代碼,題目中說,給你一棵二叉樹的中序遍曆和後序遍曆
這裡結點是在1到10000的範圍的,最多是10000個結點,不過這裡結點不是連續的不是說有N個點就是1到N編號
比如
1 7 8
1 8 7這種資料也會有的
下面是我的AC代碼
#include<cstdlib>
#include<stdio.h>
#include<string.h>
const int MAX=10005;
int in[MAX];
int post[MAX];
int son[MAX][2];
char s[1000000];
int p[MAX];
int ind,dis[MAX];
int deal(int x[],char s[])
{
int n=0,i;
for(i=0;s[i];i++)
{
if(s[i]>='0'&&s[i]<='9')
{
x[n]=0;
while(s[i]&&s[i]>='0'&&s[i]<='9')
{
x[n]=x[n]*10+s[i]-'0';
i++;
}
i--;
n++;
}
}
return n;
}
int DFS(int low,int high)
{
if(low>=high)return -1;
if(ind==-1)return -1;
int r=post[ind];
int rp=p[r];
if(rp>=low&&rp<high)
{
ind--;

son[r][1]=DFS(rp+1,high);
son[r][0]=DFS(low,rp);
return r;
}
else return -1;
}
void getDis(int r)
{
int t;
if(son[r][0]!=-1)
{
t=son[r][0];
dis[t]=dis[r]+t;
getDis(t);
}
if(son[r][1]!=-1)
{
t=son[r][1];
dis[t]=dis[r]+t;
getDis(t);
}
}
void inorder(int r)
{
if(son[r][0]!=-1)inorder(son[r][0]);
printf("%d ",r);
if(son[r][1]!=-1)inorder(son[r][1]);
}
void postorder(int r)
{
if(son[r][0]!=-1)postorder(son[r][0]);

if(son[r][1]!=-1)postorder(son[r][1]);
printf("%d ",r);
}
int main()
{
int n,i,k;
while(gets(s))
{
n=deal(in,s);
gets(s);
n=deal(post,s);
if(n==1)
{
printf("%d\n",in[0]);
continue;
}
memset(son,0,sizeof(son));
for(i=0;i<n;i++)p[in[i]]=i;
ind=n-2;

......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.