二叉树先序遍历——144. Binary Tree Preorder Traversal

来源:互联网 发布:螺钿鱼骨项链淘宝网 编辑:程序博客网 时间:2024/05/21 09:36

144. Binary Tree Preorder Traversal

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

Subscribe to see which companies asked this question.

/** * https://leetcode.com/problems/binary-tree-preorder-traversal/#/description *  * Definition for a binary tree node. * function TreeNode(val) { *     this.val = val; *     this.left = this.right = null; * } *//** * @param {TreeNode} root * @return {number[]} *//** * 先序遍历非递归 * 1.申请一个stack,如果根节点存在,将根节点push到stack中 * 2.从stackpop一个节点,执行操作后,如果右边还是存在push到stack中,如果左边还是存在push到stack中 * 3.重复2直到stack为空 */    var preorderTraversal = function(root) {        var stack = [],            node,            result = [];        if (!root) return result;        stack.push(root);        while (stack.length) {            node = stack.pop();            result.push(node.val);            if (node.right) stack.push(node.right);            if (node.left) stack.push(node.left);        }        return result;    };


阅读全文
0 0
原创粉丝点击