Skip to content

Commit

Permalink
chore: format
Browse files Browse the repository at this point in the history
  • Loading branch information
luzhipeng committed Jul 17, 2019
1 parent fcdecd9 commit 474c3c9
Showing 1 changed file with 38 additions and 37 deletions.
75 changes: 38 additions & 37 deletions problems/144.binary-tree-preorder-traversal.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
## 题目地址

https://leetcode.com/problems/binary-tree-preorder-traversal/description/

## 题目描述
Expand Down Expand Up @@ -32,23 +33,22 @@ Follow up: Recursive solution is trivial, could you do it iteratively?
## 关键点解析

- 二叉树的基本操作(遍历)
> 不同的遍历算法差异还是蛮大的
> 不同的遍历算法差异还是蛮大的
- 如果非递归的话利用栈来简化操作

- 如果数据规模不大的话,建议使用递归

- 递归的问题需要注意两点,一个是终止条件,一个如何缩小规模

1. 终止条件,自然是当前这个元素是null(链表也是一样)
1. 终止条件,自然是当前这个元素是 null(链表也是一样)

2. 由于二叉树本身就是一个递归结构, 每次处理一个子树其实就是缩小了规模,
难点在于如何合并结果,这里的合并结果其实就是`mid.concat(left).concat(right)`,
mid是一个具体的节点,left和right`递归求出即可`

难点在于如何合并结果,这里的合并结果其实就是`mid.concat(left).concat(right)`,
mid 是一个具体的节点,left 和 right`递归求出即可`

## 代码

* 语言支持:JS,C++
- 语言支持:JS,C++

JavaScript Code:

Expand All @@ -67,22 +67,22 @@ JavaScript Code:
* Testcase Example: '[1,null,2,3]'
*
* Given a binary tree, return the preorder traversal of its nodes' values.
*
*
* Example:
*
*
*
*
* Input: [1,null,2,3]
* ⁠ 1
* ⁠ \
* ⁠ 2
* ⁠ /
* ⁠ 3
*
*
* Output: [1,2,3]
*
*
*
*
* Follow up: Recursive solution is trivial, could you do it iteratively?
*
*
*/
/**
* Definition for a binary tree node.
Expand All @@ -96,35 +96,36 @@ JavaScript Code:
* @return {number[]}
*/
var preorderTraversal = function(root) {
// 1. Recursive solution

// if (!root) return [];

// return [root.val].concat(preorderTraversal(root.left)).concat(preorderTraversal(root.right));

// 2. iterative solutuon

if (!root) return [];
const ret = [];
const stack = [root];
let t = stack.pop();

while(t) {
ret.push(t.val);
if (t.right) {
stack.push(t.right);
}
if (t.left) {
stack.push(t.left);
}
t =stack.pop();
// 1. Recursive solution

// if (!root) return [];

// return [root.val].concat(preorderTraversal(root.left)).concat(preorderTraversal(root.right));

// 2. iterative solutuon

if (!root) return [];
const ret = [];
const stack = [root];
let t = stack.pop();

while (t) {
ret.push(t.val);
if (t.right) {
stack.push(t.right);
}
if (t.left) {
stack.push(t.left);
}
t = stack.pop();
}

return ret;
return ret;
};

```

C++ Code:

```C++
/**
* Definition for a binary tree node.
Expand Down

0 comments on commit 474c3c9

Please sign in to comment.