与天地兮比寿,与日月兮齐光。这篇文章主要讲述[Algorithm] 94. Binary Tree Inorder Traversal iteratively approach相关的知识,希望能为你提供帮助。
Given a binary tree, return the inorder traversal of its nodes‘ values.
Example:
Input: [1,null,2,3] 1 2 / 3Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
/** * Definition for a binary tree node. * function TreeNode(val) { *this.val = val; *this.left = this.right = null; * } */function getLefts(root) { if (!root) { return []; }let result = []; let current = root; while(current) { result.push(current); current = current.left ; }return result; }/** * @param {TreeNode} root * @return {number[]} */ var inorderTraversal = function(root) { let lefts = getLefts(root); let result = []; while (lefts.length) { let newRoot = lefts.pop(); result.push(newRoot.val); if (newRoot.right) { let newLefts = getLefts(newRoot.right); lefts = lefts.concat(newLefts) } }return result; };
【[Algorithm] 94. Binary Tree Inorder Traversal iteratively approach】The idea is
- get all the left side node and push into stack
- because stack is first in last out, when we do pop(), we are actually start from bottom of the tree.
- everytime, we pop one node from stack, we check its right child, get all the left nodes from this right child and append into stack.
- in this way, we are able to track all the node.
推荐阅读
- C++入门——指针与数组——Expression: _CrtIsValidHeapPointer(Block)
- 通过Charles设置App页面返回值的显示,检查数字是否异常显示
- C# 如何添加自定义键盘处理事件 如何配置app.config ? | csharp key press event tutorial and app.config
- 导入项目后,http://schemas.android.com/apk/res/android报错
- Android Fastboot 与 Recovery 和刷机千山万水迷了鹿
- 手动安装Android abb 包方法与心得
- Android的消息机制之ThreadLocal的工作原理
- uniapp里组件传值的异常情况(Watch方法的使用)
- Appendix 2- Lebesgue integration and Reimann integration