树常用操作:
一.遍历
遍历主要分为按层遍历(广度优先遍历)、深度优先遍历。
1.按层遍历:
核心代码:
//队列
Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
//记录当前的结点
TreeNode cur;
//入队
queue.offer(root);
while(!queue.isEmpty()){
//出队
cur = queue.poll()
if(cur.left!=null){
queue.offer(cur.left);
}
if(cur.right!=null){
queue.offer(cur.right);
}
}
2.深度优先遍历:
又分为递归和非递归。
递归:
核心代码:
public void depthTraversal(TreeNode root)
{
if (root!=null)
{
depthTraversal(root.left);
depthTraversal(root.right);
}
}
非递归:
核心代码
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode tree=stack.pop();
if(tree.right!=null)
stack.push(tree.right);
if(tree.left!=null)
stack.push(tree.left);
}