814. Binary Tree Pruning(leetcode) (tree traverse)

时间:2022-10-07 16:14:04

https://leetcode.com/contest/weekly-contest-79/problems/binary-tree-pruning/ -- 814 from leetcode

tree traverse (post traverse) left right and root

the model

void traverse(node){
if(node.left!=null) traverse(node.left);
if(node.right!=null) traverse(node.right);
//do something, current node is the deep leaf(left or right)
}

another model

int traverse(node){
if(node.left!=null) l = traverse(node.left); // value is its left child
if(node.right!=null) r = traverse(node.right); // value of its right child
//do something, current node is the deep leaf(left or right)
return node.val;
}

This problem we use second model and check if the children are null(tag ==2 : two children are nulls)

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
int val = traverse(root);
if(val == 0 && root.left==null && root.right==null) root=null;
return root;
}
int traverse(TreeNode node){//when for
//lright root
int tag = 0;
if(node.left!=null){
int l = traverse(node.left);//retur the vale of next layer(left child)
if(l==0) {
node.left = null;
tag ++;
} }else tag++;
if(node.right!= null){
int r = traverse(node.right);
if(r== 0) {
node.right = null;
tag ++;
}
}else tag ++;
//root
if(node.val==0 && tag==2)//remove this node
return 0;
else return 1;
}
}

ziji youdian cai(newbie) I only figured out one problem from the contest.