声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com
Description
Given a binary tree, return the inorder traversal of its nodes’ values.
Brief
中序非递归遍历二叉树。
Input
Output
[1,3,2]
Explanation
Recursive solution is trivial, could you do it iteratively?
Ideas
需要用到栈。先一直遍历根节点的左子树(左),然后将根节点加入到结果中(根),然后将迭代的节点变为节点的右子树即可。
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if(root == null){
return res;
}
TreeNode cur = root;
Stack<TreeNode> stack = new Stack<>();
while(cur != null || !stack.isEmpty()){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
res.add(cur.val);
cur = cur.right;
}
return res;
}
}
声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com