题目
https://leetcode-cn.com/problems/binary-tree-paths/
思路
- dfs + 递归
- dfs + 栈
code
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {string[]}
*/
var binaryTreePaths = function (root) {
let res = [];
// dfs(res, root, '');
dfs_plus(res, root);
return res;
};
var dfs = function (res, root, path) {
if (root) {
path += root.val;
if (!root.left && !root.right) {
res.push(path);
} else {
path += "->";
dfs(res, root.left, path);
dfs(res, root.right, path);
}
}
}
var dfs_plus = function (res, root) {
if (root == null) return [];
let node_s = [];
let path_s = [];
node_s.push(root);
path_s.push(root.val.toString());
while (node_s.length) {
// console.log("node_s:", node_s);
// console.log("path_s:", path_s);
let tmp_node = node_s.pop();
let tmp_path = path_s.pop();
// console.log("tmp_node:", tmp_node);
// console.log("tmp_path:", tmp_path);
if (!tmp_node.left && !tmp_node.right) {
res.push(tmp_path);
} else {
tmp_path += "->";
if (tmp_node.right) {
// tmp_path += tmp_node.right.val;
path_s.push(tmp_path + tmp_node.right.val);
node_s.push(tmp_node.right);
}
if (tmp_node.left) {
// tmp_path += tmp_node.left.val;
path_s.push(tmp_path + tmp_node.left.val);
node_s.push(tmp_node.left);
}
}
}
return res;
}