Showing posts with label . Show all posts
Showing posts with label . Show all posts

Sunday, February 23, 2014

[LEETCODE] Binary Tree Postorder Traversal



[LEETCODE] 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].

思路:
Postorder: 左右中。

注意点:
1. Recursive method iterate 条件先判断root 是否存在.
2. 对于Non-recursive method. 用两个vector,vector1存树上的node,vector2存值;
    1) 开始的判断root是否为NULL 不要忘了,且在vector1中存入root;
    2) 循环结束条件为vector1为空; 循环内容是,存node值到vector2,存node的左右(先左后右)node到vector1
    3) vector2存的顺序是反的,所以最后用一个reverse()函数


[LEETCODE]Evaluate Reverse Polish Notation


[LEETCODE] Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

思路:
不是运算符的时候入栈,遇到运算符的时候出栈两个数字,计算新的值然后再入栈。

注意点:
1. string to integer 的处理, 使用函数 stoi();
2. 最后的结果是栈的最上面一个数。
3. 注意先出栈的是算式右边的数字,后出栈的是左边的,搞错了的话运算除法分母为0就错了